iOS: 學習筆記, 用代碼驅動自動布局執行個體(swift)

來源:互聯網
上載者:User

標籤:des   style   class   blog   code   tar   

iOS自動布局是設定iOS介面的利器.
本執行個體展示了如何使用自動布局語言設定水平布局, 垂直布局
1. 建立空白iOS項目(swift)
2. 添加一個控制器類, 修改YYAppDelegate.swift檔案

@UIApplicationMainclass AppDelegate: UIResponder, UIApplicationDelegate {                                var window: UIWindow?    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)        // Override point for customization after application launch.        self.window!.backgroundColor = UIColor.whiteColor()        self.window!.makeKeyAndVisible()                self.window!.rootViewController = MainViewController(nibName: nil, bundle: nil)                return true    }

3. 修改控制器類

////  MainViewController.swift//  UIByCode3_AutoLayout////  Created by yao_yu on 14-6-17.//  Copyright (c) 2014 yao_yu. All rights reserved.//import UIKitclass MainViewController: UIViewController {        var viewMoveBlock: UIView! = UIView()    init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)    }    override func viewDidLoad() {        super.viewDidLoad()                self.viewMoveBlock.backgroundColor = UIColor.blueColor()        self.viewMoveBlock.frame = CGRectMake(100, 100, 20, 20);        self.view.addSubview(self.viewMoveBlock)                var commandPane = UIView(frame:CGRectMake(0, 0, 160, 40)) //as UIView        self.view.addSubview(commandPane)                let BUTTONSIZE:CGFloat = 40        var commands: Dictionary<String, UIButton> = [:]        var action:String        for name in ["Left", "Right", "Up", "Down", "In", "Out"]        {            var button = UIButton.buttonWithType(UIButtonType.System) as UIButton            button.setTitle(name, forState: UIControlState.Normal)            button.setTranslatesAutoresizingMaskIntoConstraints(false)            button.addTarget(self, action: Selector("move\(name)"), forControlEvents: UIControlEvents.TouchUpInside)            commands["btn\(name)"] = button            commandPane.addSubview(button)        }                var views = ["commandPane": commandPane]                commandPane.setTranslatesAutoresizingMaskIntoConstraints(false)        self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("[commandPane(260)]", options:NSLayoutFormatOptions(0), metrics:nil, views:views))        self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[commandPane(50)]", options:NSLayoutFormatOptions(0), metrics:nil, views:views))        self.view.addConstraint(NSLayoutConstraint(item: commandPane, attribute:NSLayoutAttribute.CenterX ,relatedBy:NSLayoutRelation.Equal, toItem:self.view ,attribute:NSLayoutAttribute.CenterX, multiplier:1.0, constant:0.0))                let metrics = ["SIZE": 40]        for (k,v) in commands {            v.setTranslatesAutoresizingMaskIntoConstraints(false)            commandPane.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[\(k)(SIZE)]", options:NSLayoutFormatOptions(0), metrics:metrics, views:commands))        }        commandPane.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[btnLeft(SIZE)][btnRight(SIZE)][btnUp(SIZE)][btnDown(SIZE)]-(>=0)-[btnOut(SIZE)][btnIn(SIZE)]|", options:NSLayoutFormatOptions(0), metrics:metrics, views: commands))            }    func moveLeft()    {        self.moveTo(-20, 0)    }        func moveRight()    {        self.moveTo(20, 0)    }        func moveUp()    {        self.moveTo(0, -20)    }        func moveDown()    {        self.moveTo(0, 20)    }        func moveOut()    {        var rect = self.viewMoveBlock.frame;                rect.origin.x -= 20;        rect.origin.y -= 20;        rect.size.width += 40;        rect.size.height += 40;                UIView.beginAnimations(nil, context: nil)        UIView.setAnimationDuration(1.0)                self.viewMoveBlock.frame = rect;        UIView.commitAnimations()    }        func moveIn()    {        var rect = self.viewMoveBlock.frame;                rect.origin.x += 20;        rect.origin.y += 20;        rect.size.width -= 40;        rect.size.height -= 40;                UIView.beginAnimations(nil, context: nil)        UIView.setAnimationDuration(1.0)                self.viewMoveBlock.frame = rect;        UIView.commitAnimations()    }        func moveTo(x: CGFloat, _ y: CGFloat)    {        var p = self.viewMoveBlock.center;                p.x += x;        p.y += y;                UIView.beginAnimations(nil, context: nil)        UIView.setAnimationDuration(1.0)                self.viewMoveBlock.center = p;        UIView.commitAnimations()    }    override func didReceiveMemoryWarning() {        super.didReceiveMemoryWarning()        // Dispose of any resources that can be recreated.    }        /*    // #pragma mark - Navigation    // In a storyboard-based application, you will often want to do a little preparation before navigation    override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {        // Get the new view controller using [segue destinationViewController].        // Pass the selected object to the new view controller.    }    */}

4. 運行

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.