Swift中Category的使用

前端之家收集整理的这篇文章主要介绍了Swift中Category的使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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

UIButton+Category.Swift

import UIKit

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 } }

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

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
}()

现在可以这么写

private lazy var button: UIButton = UIButton.creatButton("icon_button",title: "进入")

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

private lazy var button: UIButton {
    let btn = UIButton = UIButton.creatButton("icon_button",title: "进入")
    //红色按钮
    btn.backgroundColor = UIColor.redColor()
    return btn
}()
原文链接:https://www.f2er.com/swift/324016.html

猜你在找的Swift相关文章