Swift语言工厂设计模式和抽象工厂设计模式

前端之家收集整理的这篇文章主要介绍了Swift语言工厂设计模式和抽象工厂设计模式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

工厂设计模式封装UI控件

2.1扩展label。

1)cmd + n—>新建一个Swift File—>将导入的框架改为 import UIKit

2)写一个扩展extension—>写一个类方法 class func 一定要有返回值 可以传参数

extension UILabel {
class func labelWith(text: String,fontSize: CGFloat,textColor: UIColor)-> let l = UILabel()

l.
text = text
l.
textColor = textColor

l.font = UIFont.systemFontOfSize(fontSize)

l.textAlignment = .Center
l.
numberOfLines = 0

//自适应大小
l.sizeToFit()
return l
}

}

再懒加载创建label时的代码

private lazy var tipLabel: UILabel = UILabel.labelWith("",fontSize: 14,175);">UIColor.darkGrayColor())

2.2扩展Button。 cmd+shift+f “搜索"

import UIKit


UIButton {

//第一种按钮样式:背景视图+文字

func buttonWithTitle(backgroundImage: UIColor,175);">CGFloat) -> UIButton {
let btn = UIButton()

btn.
setBackgroundImage(UIImage(named: backgroundImage),forState:.Normal)

btn.setTitle(title,forState: .Normal)

btn.setTitleColor(titleColor,forState: .Normal)
设置按钮中文字的字体。
btn.titleLabel?.font = UIFont.systemFontOfSize(fontSize)

btn.
return btn
}
第二种按钮样式:图片+背景视图
func buttonWithImage(imageName: String) -> setImage(UIImage(named: imageName),forState: .Normal)
btn.
UIImage(named: imageName + "_highlighted"),forState: .Highlighted)

btn.
UIImage(named: backgroundImageName),175);">UIImage(named: backgroundImageName + return btn

}

}

3.抽象工厂设计模式 类簇(NSNumber,NSString,NSArray,NSDictionary):NSNumber 类 就是 使用抽象工厂设计模式来实现。

import UIKit

抽象类

所有的UI控件,都是通过这个类来进行实例化
//NSNumber
就是 使用抽象工厂设计模式来实现

class UIFactory {

抽象方法

func labelFactory(text: labelWith(text,fontSize: fontSize,textColor: textColor)

return l
}

UIButton.buttonWithTitle(backgroundImage,title: title,titleColor: titleColor,fontSize: fontSize)

return btn
}
buttonWithImage(imageName,backgroundImageName: backgroundImageName)
return btn

}

}

原文链接:https://www.f2er.com/swift/324321.html

猜你在找的Swift相关文章