整理 Swift 开发用到的一些小技巧
Selectorimport UIKit private extension Selector { static let open = #selector(TestViewController.open(sender:)) } class TestViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let openBtn : UIButton = UIButton() openBtn.addTarget(self,action: .open,for: .touchUpInside) view.addSubview(openBtn) } @objc fileprivate func open(sender: UIButton) { } } 用 UIView....在写一个 let view : UIView = UIView() view.backgroundColor = .red 但其实,还可以用另外一种写法: let view : UIView = { let tempView : UIView = UIView() tempView.backgroundColor = .red return tempView }() 这样写,其实可以很好的隔离代码,看起来也更加方便。 UIView *view = ({ UIView *tempView = [[UIView alloc] initWithFrame:CGRectMake(0,200,200)]; tempView.backgroundColor = [UIColor yellowColor]; tempView; }); 常量,还有一些什么鬼
// 定义这样的一个结构体 struct Fonts { static let content : UIFont = UIFont.systemFont(ofSize: 14.0) } // 使用 titleLabel.font = Fonts.content 同样,也适用于 // 定义这样的一个结构体 struct Colors { static let title : UIColor = UIColor(red: 190.0/255.0,green: 180.0/255.0,blue: 170.0/255.0,alpha: 1) } // 使用 label.textColor = Colors.title 对于 extension UIColor { static let title : UIColor = UIColor(red: 190.0/255.0,alpha: 1) } label.textColor = .title for-in在 for(int i = 0; i < 5; i++ ) { } 但是在 let arr = [1,2,3] // 第一种方式 for element in xxArr { print(element) } log:1 2 3 // 第二种方式,如需使用到 序号 for i in 0..<arr.count { print("(i):(arr[i])") } log:0:1 1:2 2:3 // 第三种方式 for (index,element) in arr.enumerated() { print("(index):(element)") } log:0:1 1:2 2:3 如果,配合上 for (index,element) in arr.enumerated() where index < 2 { print("(index):(element)") } log:0:1 1:2 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |