请注意版本,Swift 3.0对应的是xcode 8,网上很多例子都是旧的,在xcode 8跑不起来。
扩展是向一个已有的类、结构体或枚举类型添加新的功能(在swift中扩展没有名字)。
相当于Objective-C中Category(OC中可以有名字的,而且只能扩展类)。以下例子是扩展UIView,来获取UIView上级的UIViewController。
import UIKit
extension UIView {
/// Get the controller that this view belongs to. It will return nil if there is no controller.
///
/// - returns: UIViewController?
public func viewController() -> UIViewController? {
var next = self.next
while next != nil {
if let ret = next?.isKind(of: UIViewController.superclass()!) {
return next as? UIViewController
}
next = next?.next
}
return nil
}
}
也可以扩展方法来封装频繁重复的操作。
以下例子为创建固定格式的UIButton。
import UIKit
extension UIButton {
/// Create simple button
///
/// - parameter imageName: image name, can set to be nil
/// - parameter title: title name
///
/// - returns: button
public func creatButton(imageName:String?, title:String) -> UIButton {
let button = UIButton()
if ((imageName?.characters.count) != nil) {
button.setImage(UIImage(named: imageName!), for: UIControlState.normal)
}
button.setTitle(title, for: UIControlState.normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
button.setTitleColor(UIColor.darkGray, for: UIControlState.normal)
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
return button
}
}