在 iOS 開發中,UI 元件可以透過 Storyboard 或 Xib 拉線建立,也可以完全用程式碼動態建立。本文整理 IBAction、IBOutlet、frame、center、bounds 以及動畫等基礎概念。
IBAction 通常用於宣告可連線的事件方法,本質上等同 void 方法:
- (IBAction)buttonClicked:(id)sender;
IBOutlet 用於宣告可連線的屬性:
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
若出現:
setValue:forUndefinedKey:]: this class is not key value coding
通常代表連線出問題,例如 outlet 或 action 指向不存在的屬性或方法。檢查 Storyboard 連線即可解決。
frame 可修改位置與尺寸:
CGRect btnFrame = self.controlName.frame;
btnFrame.origin.y -= 10;
self.controlName.frame = btnFrame;
center 可修改中心點位置:
CGPoint tempCenter = self.head.center;
tempCenter.x += 10;
self.head.center = tempCenter;
bounds 可修改尺寸:
CGRect tempBounds = self.head.bounds;
tempBounds.size.width += 20;
self.head.bounds = tempBounds;
UIButton *btn = [[UIButton alloc] init];
[self.view addSubview:btn];
btn.frame = CGRectMake(100, 100, 100, 100);
btn.backgroundColor = [UIColor blueColor];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:2.0];
CGRect tempBounds = self.head.bounds;
tempBounds.size.width += 50;
tempBounds.size.height += 50;
self.head.bounds = tempBounds;
[UIView commitAnimations];
掌握這些基礎後,就能更靈活地在 Storyboard 與純程式碼之間切換,也能更準確地進行 UI 布局與互動設計。