Swift3.0中Category的使用

来源:互联网 发布:新房装修 淘宝 推荐 编辑:程序博客网 时间:2024/06/04 18:52

在项目开发中,经常会遇到同一个控件被频繁的创建,可能他们之间只是某些属性值不同而已,这个时候我们可以使用工厂模式去创建这些控件,也可以使用Category,在这里我们介绍如何使用Category

例如:按钮UIButton被频繁创建好多次,这时我们可以创建一个Swift文件:

UIButton+Category.Swift

import UIKitswift 2.3:extension UIButton {    //把按钮直接不同属性的名字传进来,在这里我们传进来图片名字和标题    class func creatButton(imageName:String, title:String) -> UIButton {        let button = UIButton()        button.setImage(UIImage(named: imageName), forState: UIControlState.Normal)        button.setTitle(title, forState: UIControlState.Normal)        button.titleLabel?.font = UIFont.systemFontOfSize(12)        button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)        button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)        return button    }}swift3.0:extension UIButton {    class func creatButton(imageName:String, title:String) -> UIButton {        let button = UIButton()        button.setImage(UIImage.init(named: imageName), for: .normal)        button.setTitle(title, for: .normal)        button.titleLabel?.font = UIFont.systemFont(ofSize: 12)        button.setTitleColor(UIColor.darkGray, for: .normal)        button.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0)        return button    }}

在创建按钮的地方,本来要这么写

swift2.3:private lazy var button: UIButton {    let btn = UIButton()    btn.setImage(UIImage(named: "icon_button"), forState: UIControlState.Normal)    btn.setTitle("进入", forState: UIControlState.Normal)    btn.titleLabel?.font = UIFont.systemFontOfSize(12)    btn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)    btn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)    return btn}()swoft3.0:private var button: UIButton {    let button = UIButton();    button.setImage(UIImage.init(named: "icon_button"), for: .normal)    button.setTitle("进入", for: .normal)    button.backgroundColor = UIColor.red    button.titleLabel?.font = UIFont.systemFont(ofSize: 12)    button.setTitleColor(UIColor.darkGray, for: .normal)    button.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0)    return button}

现在可以这么写

swift2.3:private lazy var button: UIButton = UIButton.creatButton("icon_button", title: "进入")swift3.0:private var button: UIButton = UIButton.creatButton(imageName: "icon_button", title: "进入")

如果个别按钮需要额外加一些属性,可以这么写

swift2.3:private lazy var button: UIButton {    let btn = UIButton = UIButton.creatButton("icon_button", title: "进入")    //红色按钮    btn.backgroundColor = UIColor.redColor()    return btn}()swift3.0:private  var button: UIButton {    let button = UIButton.creatButton(imageName: "icon_button", title: "进入")    button.backgroundColor = UIColor.red    return button}
0 0