這是筆者在博客園寫的第一篇部落格,前幾天因種種原因決定離開待了幾年的 CSDN,希望在博客園有個新的開始。
Foundation 框架裡的 frame 可說是大家最熟悉的屬性之一,但修改起來頗為麻煩。它是 CGRect 型別,而 CGRect 是結構體——結構體裡的某個屬性若想單獨修改是不允許的,必須像下面這樣先取出、改一下再重新賦回去,也就是常說的「三部曲」。

如果結構體的屬性也能直接修改,那會有多爽快?就像下面這樣:

其實只要自己為 UIView 寫個分類,用這個分類來取代 frame 即可。大致思路是透過分類為 UIView 多增加 x、y、width、height 四個屬性,每個屬性都各自實作 getter 與 setter,如此一來 frame 便可拋在一邊了。
分類 UIView+Frame 宣告:
#import <UIKit/UIKit.h> @interface UIView (Frame) // 模仿 frame 寫出它的四個屬性 @property (nonatomic, assign) CGFloat x; @property (nonatomic, assign) CGFloat y; @property (nonatomic, assign) CGFloat width; @property (nonatomic, assign) CGFloat height; @end
分類 UIView+Frame 實作:
#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)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;
}
@end
之後在需要的地方 Import 一下:

就能輕鬆地對各 UI 控制項的 frame 做單獨修改了。