在iOS中view的frame属性使用地太频繁了,尤其是调UI的时候。我们知道,正常情况下我们无法对frame的某个属性(x,y,width,height等)进行单独修改,比如: someView.frame.x = 100; 这种方式是不允许的,但实际上我们更经常遇到的是frame的大部分元素值保持不变,只改变其中的一部分。相信这个烦恼困扰了不少人,于是我们不得不用以下两种方法去达到目的: 法1: CGRect frame = someView.frame; frame.x =100; frame.width = 200; someView.frame = frame; 法2: someView.frame = CGRectMake(100, XXX, 200, XXX); 法2看起来也很精简,但实际上也很麻烦,因为实际应用场景中x, y, width, height四个值都是依赖别的变量,导致法2的语句非常长。简而言之,以上方法都不够“优雅”。那怎样才算优雅呢?我觉得如果我们能如下这样直接修改某个值就完美了: someView.x = 100; someView.width = 200; 我们跳过someView的frame属性,直接修改了我们想要的元素值。幸运的是,我们使用category可以相当方便地达到目的,这是一件一劳永逸的事情,引入一次category后整个工程都可以使用这种修改方法: UIView+Frame.h WZLCodeLibrary Created by wzl on 15/3/23. Copyright (c) 2015年 Weng-Zilin. All rights reserved. #import <UIKit/UIKit.h> @interface UIView (Frame) @property (nonatomic, assign) CGFloat x; @property (nonatomic, assign) CGFloat y; @property (nonatomic, assign) CGFloat width; @property (nonatomic, assign) CGFloat height; @property (nonatomic, assign) CGPoint origin; @property (nonatomic, assign) CGSize size; @end UIView+Frame.m WZLCodeLibrary #import "UIView+Frame.h" @implementation UIView (Frame) - (void)setX:(CGFloat)x { CGRect frame = self.frame; frame.origin.x = x; self.frame = frame; } - (CGFloat)x { return self.frame.origin.x; } - (void)setY:(CGFloat)y { CGRect frame = self.frame; frame.origin.y = y; self.frame = frame; } - (CGFloat)y { return self.frame.origin.y; } - (void)setOrigin:(CGPoint)origin { CGRect frame = self.frame; frame.origin = origin; self.frame = frame; } - (CGPoint)origin { return self.frame.origin; } - (void)setWidth:(CGFloat)width { CGRect frame = self.frame; frame.size.width = width; self.frame = frame; } - (CGFloat)width { return self.frame.size.width; } - (void)setHeight:(CGFloat)height { CGRect frame = self.frame; frame.size.height = height; self.frame = frame; } - (CGFloat)height { return self.frame.size.height; } - (void)setSize:(CGSize)size { CGRect frame = self.frame; frame.size = size; self.frame = frame; } - (CGSize)size { return self.frame.size; } @end
时间: 2024-11-14 12:28:55