您的位置:首页 > 移动开发 > Swift

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

2016-03-13 00:00 330 查看
摘要: 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)-> UILabel {
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, textColor: UIColor.darkGrayColor())

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

import UIKit

extension UIButton {

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

class func buttonWithTitle(backgroundImage: String,title: String, titleColor: UIColor,fontSize: 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.sizeToFit()
return btn
}
//第二种按钮样式:图片+背景视图
class func buttonWithImage(imageName: String,backgroundImageName: String) -> UIButton {
let btn = UIButton()

btn.setImage(UIImage(named: imageName), forState: .Normal)
btn.setImage(UIImage(named: imageName + "_highlighted"), forState: .Highlighted)

btn.setBackgroundImage(UIImage(named: backgroundImageName), forState: .Normal)
btn.setBackgroundImage(UIImage(named: backgroundImageName + "_highlighted"), forState: .Highlighted)

return btn

}

}

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

import UIKit

//抽象类

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

class UIFactory {

//抽象方法

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

return l
}

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

class func buttonWithTitle(backgroundImage: String,title: String, titleColor: UIColor,fontSize: CGFloat) -> UIButton {
let btn = UIButton.buttonWithTitle(backgroundImage, title: title, titleColor: titleColor, fontSize: fontSize)

return btn
}
//第二种按钮样式:图片+背景视图
class func buttonWithImage(imageName: String,backgroundImageName: String) -> UIButton {
let btn = UIButton.buttonWithImage(imageName, backgroundImageName: backgroundImageName)
return btn

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: