Swift 中的类是灵活构造的构建块。与常量、变量和函数类似,用户可以定义类属性和方法。
在这种情况下,您不需要创建Class。有关我的声明的更多信息,您可以查看here:
这可能会浪费资源,很少有 UILabel 自定义不能证明子类化是合理的。
您可以创建一个更有用的文件,例如命名为 Utils.swift,其中包含您的方法集合:
import UIKit
func addView(title:String, fontColor:UIColor, fontType:UIFont, bgColor:UIColor, x:CGFloat, y:CGFloat, width:CGFloat, height:CGFloat) -> UILabel {
let myView = UILabel()
myView.text = title
myView.sizeToFit()
myView.numberOfLines = 0
myView.textColor = fontColor
myView.font = fontType
myView.backgroundColor = bgColor
myView.frame = CGRectMake(x, y, width, height)
return myView
}
在 Swift 中,您不需要将文件导入其他类,因此在您的类中您可以这样做:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let myLabel = addView("hello world",fontColor:UIColor.redColor(),fontType:UIFont(name: "HelveticaNeue-UltraLight", size: 30),bgColor:UIColor.redColor(),x:0,y:0,width:200,height:25)
self.view.addsubview(myLabel)
}
}
否则,如果您需要对UILabel 进行子类化以进行相关变化:
import UIKit
class MyCustomLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
sharedInit()
}
init(title: String, fontColor: UIColor, fontType: UIFont, bgColor: UIColor, x: CGFloat, y: CGFloat, width:CGFloat, height: CGFloat){
let frame = CGRectMake(x, y, width, height)
super.init(frame: frame)
self.text = title
self.sizeToFit()
self.numberOfLines = 0
self.textColor = textColor
self.font = fontType
self.backgroundColor = bgColor
sharedInit()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sharedInit()
}
func sharedInit() {
userInteractionEnabled = true
// add others common init features..
}
}