- OC
UIView *redView = [[UIView alloc]initWithFrame:CGRectMake(0, 30, 100, 100)];
redView.backgroundColor = [UIColor redColor];
[self.view addSubview:redView];
Swift
let a = 10; let b = 20
// 定義一個常量,視圖
let v = UIView(frame: CGRect(x: 0, y: 20, width: 100, height: 100))
v.backgroundColor = UIColor.redColor()
// 調(diào)用方法統(tǒng)一使用 .
self.view.addSubview(v)
2. OC 類方法
[UIColor redColor];
Swift UIColor.redColor
UIColor.redColor
3. OC 的枚舉 UIButtonTypeContactAdd
Swift 中 UIButtonType.ContactAdd
1> 可以直接省略前綴 .ContactAdd,但是 Xcode 的智能提示有的時候不給力
2> 如果沒有智能提示,可以直接 `回車`,`->`,`.`
4. 監(jiān)聽方法
OC 使用 @selector(actionName)
Swift 直接使用字符串逻卖,提示:可以先用智能提示敲出方法名,然后增加引號
oc
-(void)test{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(didClick:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)didClick:(UIButton*)button{
}
swift
// 創(chuàng)建按鈕
let btn = UIButton(type: UIButtonType.ContactAdd)
v.addSubview(btn)
// 監(jiān)聽方法
btn.addTarget(self, action: "clickButton", forControlEvents: .TouchUpInside)
}
func clickButton(btn: UIButton) {
print(__FUNCTION__)
print(btn)
}
如果有參數(shù)直接增加 ':'
5. 沒有分號 - 在程序語言中昭抒,`;` 用于拆分語句评也,表示一個完整的語句結(jié)束
Swift 中,大多數(shù)情況下不需要分號