iOS開發之使用UIView-Positioning簡化頁面配置,iosuiview動畫
使用過代碼布局的人可能會有這樣的感覺,給控制項設定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的一些屬性,為代碼布局還是帶來了挺大的方便,推薦大家可以使用一下。