iOS: 学习笔记, 用代码驱动自动布局实例(swift)

iOS自动布局是设置iOS界面的利器.
本实例展示了如何使用自动布局语言设置水平布局, 垂直布局
1. 创建空白iOS项目(swift)
2. 添加一个控制器类, 修改YYAppDelegate.swift文件

@UIApplicationMain

class 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 UIKit



class 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. 运行

你可能感兴趣的:(swift)