在我们撰写OC代码时,在写UI界面或者功能的时为了增加代码的可读性和开发效率,都会创建控件的分类来进行控件的声明,那么Swift怎么创建分类呢,这篇文章就来简单的说明一下,仅供大家来参考:
1.类似于OC创建分类一样,先创建一个Swift类文件(快捷键:common+N
):
直接点击下一步,然后命名就成
2.直接撰写代码如下(UIButton和UILabel为例):
import UIKit
import Foundation
//MARK: - UILabel
extension UILabel {
convenience init(backGroundColor : UIColor, text : String, textColor: UIColor, font: CGFloat,alignMent: NSTextAlignment) {
// 便利构造方法必须依赖于指定构造方法!!!!!!!!!!!!!!
self.init()
self.backgroundColor = backGroundColor;
self.text = text;
self.textColor = textColor;
self.font = FONT(font: font)
self.textAlignment = alignMent
}
}
//MARK: - UIButton
extension UIButton {
convenience init(type: ButtonType, cornerRadius: CGFloat, title: String, titleColor: UIColor, titleFont: CGFloat, backColor: UIColor) {
self.init()
self.backgroundColor = backColor;
self.layer.cornerRadius = cornerRadius;
self.titleLabel?.font = UIFont.systemFont(ofSize: titleFont)
self.setTitle(title, for: .normal)
self.setTitleColor(titleColor, for: .normal)
}
}
extension UIButton {
convenience init(type: ButtonType, cornerRadius: CGFloat, title: String, titleColor: UIColor, titleFont: CGFloat, backImage: String) {
self.init()
self.setBackgroundImage(UIImage(named: backImage), for: .normal)
self.layer.cornerRadius = cornerRadius
self.titleLabel?.font = UIFont.systemFont(ofSize: titleFont)
self.setTitle(title, for: .normal)
self.setTitleColor(titleColor, for: .normal)
}
}
在使用分类的时候和OC代码使用的时候是一样的,在使用的时候可以直接调用:
懒加载的调用一行代码
lazy var nextButton: UIButton = {
let nextButton = UIButton.init(type: .custom, cornerRadius: 3, title: "下一步", titleColor: UIColor.white, titleFont: ADAPTX(x: 16), backColor: RGB0X(hexValue: 0xfc0808))
nextButton.addTarget(self, action: #selector(nextDidSelected), for: .touchUpInside)
return nextButton
}()
注:label和button的调用方法是一样的操作的;