使用過代碼布局的人可能會有這樣的感覺,給控件設置frame的時候比較繁瑣。最 近在Github上看到有一個UIView的一個分類UIView-Positioning,這個分類提供了一些屬性,比如left、right、 top、bottom、centerX、centerY等,在布局的時候使用這些屬性,會更簡單和方便,下面介紹下具體使用。
UIView-Positioning的Github的地 址:https://github.com/freak4pc/UIView-Positioning,將UIView+Positioning.h和 UIView+Positioning.m文件拷貝到工程里面。
在使用代碼布局的時候,我一般習慣按照下面三個步驟去做。
1、聲明控件變量。
@implementation LoginView{ UILabel *_userNameLabel; UITextField *_userNameField;}
2、在initWithFrame方法中,創建控件并設置它的一些基本屬性,然后添加到View的子視圖中。
- (instancetype)initWithFrame:(CGRect)frame{ if (self = [super initWithFrame:frame]) { _userNameLabel = [UILabel new]; _userNameLabel.font = [UIFont systemFontOfSize:14.0]; _userNameLabel.textColor = [UIColor blackColor]; _userNameLabel.backgroundColor = [UIColor clearColor]; _userNameLabel.text = @"用戶名:"; [self addSubview:_userNameLabel]; _userNameField = [UITextField new]; _userNameField.font = [UIFont systemFontOfSize:14.0]; _userNameField.textColor = [UIColor blackColor]; _userNameField.borderStyle = UITextBorderStyleRoundedRect; [self addSubview:_userNameField]; } return self;}
3、在layoutSubViews方法里面對控件進行布局,下面使用 UIView-Positioning分類的size、left、top、bottom、centerY等屬性,通過使用right屬性,可以取到左邊 Label控件的origin.x+size.width,然后加上一個padding值,就可以得到右邊TextField控件的origin.x。平 時我們可能經常會碰到,要將兩個不同高度的控件,設置為垂直方向對齊,我這里特意將這兩個控件的高度設置得不一樣,通過將它們的centerY屬性設置為 相等,就可以保持這兩個控件在垂直方向對齊了。
- (void)layoutSubviews{ [super layoutSubviews]; CGFloat margin = 50, padding = 5; _userNameLabel.size = CGSizeMake(60, 15); _userNameLabel.left = margin; _userNameLabel.top = margin; _userNameField.size = CGSizeMake(200, 30); _userNameField.left = _userNameLabel.right + padding; _userNameField.centerY = _userNameLabel.centerY;}
UIView-Positioning通過擴展了UIView的一些屬性,為代碼布局還是帶來了挺大的方便,推薦大家可以使用一下。
新聞熱點
疑難解答