1. 程式人生 > >Swift 3.0 擴充套件(extension)的使用

Swift 3.0 擴充套件(extension)的使用

請注意版本,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
    }
    
}