Xcode8已经发布,带了Swift3的预览版本,以后都是默认采用Swift3的语法。
这个例子主要是演示iOS中如何用纯代码实现自动布局,先看看效果。
还是先创建程序入口文件main.swift
:
import UIKitlet argc = Process.argclet argv = UnsafeMutablePointer<UnsafeMutablePointer<CChar>>(Process.unsafeArgv)UIApplicationMain(argc,argv,NsstringFromClass(MainApp),NsstringFromClass(MainAppDelegate))
创建UI程序入口App.swift
,增加了一个导航栏:
import UIKitclass 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 }}
然后创建视图控制器VIEwController.swift
,在这里实现自动布局:
import UIKitclass 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 ( layputs: [ ("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 } } // 添加自动布局规则 for layout in vIEwsLayouts { self.addConstraints( NSLayoutConstraint.constraints( withVisualFormat: layout.0,options: layout.1,metrics: nil,vIEws: vIEwsMap ) ) } }}
完成。
总结以上是内存溢出为你收集整理的Swift: 你好, AutoLayout!全部内容,希望文章能够帮你解决Swift: 你好, AutoLayout!所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)