使用過代碼佈局的人可能會有這樣的感受,給控件設置frame的時候比較繁瑣。最 近在Github上看到有一個UIView的一個分類UIView-Positioning,這個分類提供了一些屬性,好比left、right、 top、bottom、centerX、centerY等,在佈局的時候使用這些屬性,會更簡單和方便,下面介紹下具體使用。git
UIView-Positioning的Github的地 址:https://github.com/freak4pc/UIView-Positioning,將UIView+Positioning.h和 UIView+Positioning.m文件拷貝到工程裏面。github
在使用代碼佈局的時候,我通常習慣按照下面三個步驟去作。佈局
一、聲明控件變量。spa
@implementation LoginView { UILabel *_userNameLabel; UITextField *_userNameField; }
二、在initWithFrame方法中,建立控件並設置它的一些基本屬性,而後添加到View的子視圖中。code
- (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; }
三、在layoutSubViews方法裏面對控件進行佈局,下面使用 UIView-Positioning分類的size、left、top、bottom、centerY等屬性,經過使用right屬性,能夠取到左邊 Label控件的origin.x+size.width,而後加上一個padding值,就能夠獲得右邊TextField控件的origin.x。平 時咱們可能常常會碰到,要將兩個不一樣高度的控件,設置爲垂直方向對齊,我這裏特地將這兩個控件的高度設置得不同,經過將它們的centerY屬性設置爲 相等,就能夠保持這兩個控件在垂直方向對齊了。blog
- (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的一些屬性,爲代碼佈局仍是帶來了挺大的方便,推薦你們可使用一下。it