您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 拖控件與程式化建立 UI 元件基礎

編輯:iOS 開發綜合

在 iOS 開發中,UI 元件可以透過 Storyboard 或 Xib 拉線建立,也可以完全用程式碼動態建立。本文整理 IBAction、IBOutlet、frame、center、bounds 以及動畫等基礎概念。

1. IBAction 與 IBOutlet

IBAction 通常用於宣告可連線的事件方法,本質上等同 void 方法:

- (IBAction)buttonClicked:(id)sender;

IBOutlet 用於宣告可連線的屬性:

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;

2. 常見錯誤

若出現:

setValue:forUndefinedKey:]: this class is not key value coding

通常代表連線出問題,例如 outlet 或 action 指向不存在的屬性或方法。檢查 Storyboard 連線即可解決。

3. frame、center、bounds

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;

4. 程式化建立按鈕

UIButton *btn = [[UIButton alloc] init];
[self.view addSubview:btn];
btn.frame = CGRectMake(100, 100, 100, 100);
btn.backgroundColor = [UIColor blueColor];

5. 簡單動畫

[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 布局與互動設計。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved