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(, , , );
self.view.addSubview(self.viewMoveBlock) var commandPane = UIView(frame:CGRectMake(, , , )) //as UIView
self.view.addSubview(commandPane) let BUTTONSIZE:CGFloat =
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(), metrics:nil, views:views))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[commandPane(50)]", options:NSLayoutFormatOptions(), 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": ]
for (k,v) in commands {
v.setTranslatesAutoresizingMaskIntoConstraints(false)
commandPane.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[\(k)(SIZE)]", options:NSLayoutFormatOptions(), metrics:metrics, views:commands))
}
commandPane.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[btnLeft(SIZE)][btnRight(SIZE)][btnUp(SIZE)][btnDown(SIZE)]-(>=0)-[btnOut(SIZE)][btnIn(SIZE)]|", options:NSLayoutFormatOptions(), metrics:metrics, views: commands)) } func moveLeft()
{
self.moveTo(-, )
} func moveRight()
{
self.moveTo(, )
} func moveUp()
{
self.moveTo(, -)
} func moveDown()
{
self.moveTo(, )
} func moveOut()
{
var rect = self.viewMoveBlock.frame; rect.origin.x -= ;
rect.origin.y -= ;
rect.size.width += ;
rect.size.height += ; 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 += ;
rect.origin.y += ;
rect.size.width -= ;
rect.size.height -= ; 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. 运行

iOS: 学习笔记, 用代码驱动自动布局实例(swift)的更多相关文章

  1. iOS: 学习笔记, 用代码驱动自动布局实例

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

  2. input子系统学习笔记六 按键驱动实例分析下【转】

    转自:http://blog.chinaunix.net/uid-20776117-id-3212095.html 本文接着input子系统学习笔记五 按键驱动实例分析上接续分析这个按键驱动实例! i ...

  3. python3.4学习笔记(十四) 网络爬虫实例代码,抓取新浪爱彩双色球开奖数据实例

    python3.4学习笔记(十四) 网络爬虫实例代码,抓取新浪爱彩双色球开奖数据实例 新浪爱彩双色球开奖数据URL:http://zst.aicai.com/ssq/openInfo/ 最终输出结果格 ...

  4. iOS学习笔记-精华整理

    iOS学习笔记总结整理 一.内存管理情况 1- autorelease,当用户的代码在持续运行时,自动释放池是不会被销毁的,这段时间内用户可以安全地使用自动释放的对象.当用户的代码运行告一段 落,开始 ...

  5. iOS学习笔记总结整理

    来源:http://mobile.51cto.com/iphone-386851_all.htm 学习IOS开发这对于一个初学者来说,是一件非常挠头的事情.其实学习IOS开发无外乎平时的积累与总结.下 ...

  6. iOS学习笔记之Category

    iOS学习笔记之Category 写在前面 Category是类别(也称为类目或范畴),使用Category,程序员可以为任何已有的类添加方法.使用类别可以对框架提供的类(无法获取源码,不能直接修改) ...

  7. iOS学习笔记之ARC内存管理

    iOS学习笔记之ARC内存管理 写在前面 ARC(Automatic Reference Counting),自动引用计数,是iOS中采用的一种内存管理方式. 指针变量与对象所有权 指针变量暗含了对其 ...

  8. iOS学习笔记06—Category和Extension

    iOS学习笔记06—Category和Extension 一.概述 类别是一种为现有的类添加新方法的方式. 利用Objective-C的动态运行时分配机制,Category提供了一种比继承(inher ...

  9. IOS学习笔记48--一些常见的IOS知识点+面试题

      IOS学习笔记48--一些常见的IOS知识点+面试题   1.堆和栈什么区别? 答:管理方式:对于栈来讲,是由编译器自动管理,无需我们手工控制:对于堆来说,释放工作由程序员控制,容易产生memor ...

随机推荐

  1. OGG 单表初始化操作步骤

    有时候ogg两端数据不一致,且数据量较大,手工修改比较复杂的情况下,我们需要对这些表进行初始化.初始化的大概思路是: 1. 停止两端OGG 2. 如果业务不可以停很长时间,就需要配置目标端进程,暂停这 ...

  2. HAProxy 基本翻译

    REF:http://cbonte.github.io/haproxy-dconv/1.5/configuration.html Proxy configuration can be located ...

  3. Windows2008安装IIS方法

    1.右键点击 “计算机”,在弹出菜单中选择“管理”选项,在服务器管理器左侧界面 点击 “角色”选项,如下图: 2.点击“添加角色”按钮后,弹出如下界面 3.选择“角色”列表中的“Web服务器(IIS) ...

  4. 闪回还原点(Flashback Restore Point)

    Flashback Restore Point(闪回还原点) 闪回还原点分两种,一种是Normal Restore Points(正常还原点),另一种是Guaranteed Restore Point ...

  5. NSURLSessionDownloadTask 断点下载

    #import "ViewController.h" #import "ASIHTTPRequest.h" #import <AFNetworking/A ...

  6. memcpy的使用方法总结

    1.memcpy 函数用于 把资源内存(src所指向的内存区域) 复制到目标内存(dest所指向的内存区域):拷贝多少个?有一个size变量控制拷贝的字节数:函数原型:void *memcpy(voi ...

  7. 关于cocos2d-x精灵加亮及变灰效果

    //根据现有CCSprite,变亮和变灰 static CCSprite* graylightWithCCSprite(CCSprite* oldSprite,bool isLight) { //CC ...

  8. Apache Kafka: Next Generation Distributed Messaging System---reference

    Introduction Apache Kafka is a distributed publish-subscribe messaging system. It was originally dev ...

  9. 5 Ways to Use Log Data to Analyze System Performance--reference

    Recently we looked across some of the most common behaviors that our community of 25,000 users looke ...

  10. Modem常用概念

    真实设备的标识,即DEVICE_ID.比如,Android设备是手机,这个DEVICE_ID可以同通过TelephonyManager.getDeviceId()获取,它根据不同的手机设备返回IMEI ...