Swift: 你好, AutoLayout!

Xcode8已經(jīng)發(fā)布,帶了Swift3的預覽版本,以后都是默認采用Swift3的語法。

這個例子主要是演示iOS中如何用純代碼實現(xiàn)自動布局,先看看效果。

ios-auto-layout.png

還是先創(chuàng)建程序入口文件main.swift:

import UIKit

let argc = Process.argc
let argv = UnsafeMutablePointer<UnsafeMutablePointer<CChar>>(Process.unsafeArgv)

UIApplicationMain(argc, argv, NSStringFromClass(MainApp), NSStringFromClass(MainAppDelegate))

創(chuàng)建UI程序入口App.swift,增加了一個導航欄:

import UIKit

class MainApp: UIApplication {
    override func sendEvent(_ event: UIEvent) {
        super.sendEvent(event)
    }
}

class MainAppDelegate: UIResponder, UIApplicationDelegate {
    
    var window: UIWindow?
    
    func application(_ app: UIApplication, didFinishLaunchingWithOptions opt: [NSObject: AnyObject]?) -> Bool {
        
        self.window = UIWindow(frame: UIScreen.main().bounds)

        self.window!.rootViewController = UINavigationController(rootViewController:MainViewController())
        self.window!.backgroundColor = UIColor.white()
        self.window!.makeKeyAndVisible()
        
        return true
    }
}

然后創(chuàng)建視圖控制器ViewController.swift, 在這里實現(xiàn)自動布局:

import UIKit

class MainViewController: UIViewController {

    var label0_: UILabel!
    var label1_: UILabel!
    var label2_: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "主視圖"

        self.label0_ = {
            let label = UILabel()
            label.textAlignment = .center
            label.text = "Hello, AutoLayout!"
            return label
        }()

        self.label1_ = {
            let label = UILabel()
            label.textColor = UIColor.red()
            label.textAlignment = .center
            label.text = "=== 你好, AutoLayout! ==="
            return label
        }()
        
        self.label2_ = {
            let label = UILabel()
            label.textColor = UIColor.blue()
            label.textAlignment = .center
            label.text = "=== 底部 ==="
            return label
        }()

        self.view.addSubview(self.label0_)
        self.view.addSubview(self.label1_)
        self.view.addSubview(self.label2_)

        self.view.setupAutoLayout {
            return (
                layouts: [
                    ("H:|-(20)-[label0]-20-|",[]),
                    ("H:|-(20)-[label1]-20-|",[]),
                    ("H:|-(20)-[label2]-20-|",[]),

                    ("V:|[topGuide]-(0)-[label0(20)]-20-[label1(20)]-(>=0)-[label2]-[bottomGuide]|",[])
                ],
                viewsMap: [
                    "topGuide": self.topLayoutGuide,
                    "bottomGuide": self.bottomLayoutGuide,
                    
                    "label0": self.label0_,
                    "label1": self.label1_,
                    "label2": self.label2_
                ]
            )
        }
    }
}

其中self.view.setupAutoLayout是針對UIView類型作的擴展:

extension UIView {
    func setupAutoLayout(closure: () -> (layouts: [(String,NSLayoutFormatOptions)], viewsMap: [String:AnyObject]) ) {
        let (viewsLayouts, viewsMap) = closure()
        
        // 采用自動布局
        for view in viewsMap.values {
            if let v = view as? UIView {
                v.translatesAutoresizingMaskIntoConstraints = false
            }
        }
        
        // 添加自動布局規(guī)則
        for layout in viewsLayouts {
            self.addConstraints(
                NSLayoutConstraint.constraints(
                    withVisualFormat: layout.0,
                    options: layout.1, metrics: nil,
                    views: viewsMap
                )
            )
        }
    }
}

完成。

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 15,419評論 4 61
  • 魚香茄子:三個茄子切成條狀,用淀粉和醬油攪拌,然后用油炸茄子上色,撈出來進行炒,放蔥,姜,蒜,鹽,雞精,味精,十彡...
    滿漢之全席閱讀 126評論 0 1
  • 接到二勇的電話,有志手已經(jīng)忍不住抖了! 他在家轉(zhuǎn)了幾圈,坐上了回老家的班車。 爸爸腦出血,已經(jīng)送到縣醫(yī)院了! 想想...
    粒粒藍雪閱讀 366評論 0 0
  • 轉(zhuǎn)載請標注: http://www.itdecent.cn/p/5e802482caa4始終覺得要理解一個龐大的東...
    wbo4958閱讀 2,280評論 0 2
  • 2017.09.23號,今晚和女兒去公婆家吃的飯,回家后我倆收拾一下床,女兒把她的玩具放了滿滿一床,我拿出歸納...
    愛孩子閱讀 288評論 0 2

友情鏈接更多精彩內(nèi)容