2016年1月

代码创建UINavigationController

首先,需要在项目设置去掉 Main Interface

在代码中自定义UIWindow对象,并设置控制器,注意,我这里用到的控制器都在关联了xib的
//
//  AppDelegate.swift
//  代码创建导航
//
//  Created by zhang on 16/1/16.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.

        // 先取消项目设置中的 Main Interface
        // 初始化窗口对象
        let window = UIWindow()

        // 初始化 navigation 对象
        // 初始化默认显示的控制器
        let mainController = UIViewControllerA()

        // 初始化 navigation
        // 这种方式设置初始化需要后面设置下默认控制器
//        let navigation = UINavigationController()
        // 在初始化的时候指定默认控制器
        let navigation = UINavigationController(rootViewController: mainController)

        // 下面的是两种设置 navigation 默认控制器的方法
//        navigation.addChildViewController(mainController)
//        navigation.pushViewController(mainController, animated: true)

        // 设置当前窗口的根控制器
        window.rootViewController = navigation

        self.window = window
        // 当前窗口作为主窗口并显示
        self.window?.makeKeyAndVisible()
        return true
    }
}
navigation的根控制器
//
//  UIViewControllerA.swift
//  代码创建导航
//
//  Created by zhang on 16/1/16.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class UIViewControllerA: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // 设置导航栏标题
        self.title = "第一个控制器"

        // 导航条左边的按钮
        let addButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: nil, action: nil)
        let cameraButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Camera, target: nil, action: nil)
        // 赋值
        self.navigationItem.leftBarButtonItems = [addButton,cameraButton]

        // 设置导航栏右边的按钮
        let composeButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Compose, target: nil, action: nil)
        let actionButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Action, target: nil, action: nil)
        self.navigationItem.rightBarButtonItems = [composeButton,actionButton]


        // 设置返回
        let backButton = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)

        self.navigationItem.backBarButtonItem = backButton
        // Do any additional setup after loading the view.
    }

    @IBAction func nextController(sender: UIButton) {
//        let controller = UIViewControllerB(nibName: "UIViewControllerB", bundle : nil)
        let controller = UIViewControllerB()
        // 把下个控制器对象加入 navigation 的栈,因为navigavtion会显示栈顶的控制器,所以,相当于跳转到下个控制器
        self.navigationController?.pushViewController(controller, animated: true)
    }
}
第二个控制器
//
//  UIViewControllerB.swift
//  代码创建导航
//
//  Created by zhang on 16/1/16.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class UIViewControllerB: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "第二个控制器"

        // Do any additional setup after loading the view.
    }
    // 返回
    @IBAction func back(sender: AnyObject) {
        // 移除当前控制器,回到上一个,相当于返回
        self.navigationController?.popViewControllerAnimated(true)
    }
    // 跳转到下个controller
    @IBAction func next(sender: AnyObject) {
        let controller = UIViewControllerC()
        self.navigationController?.pushViewController(controller, animated: true)
    }
}
第三个控制器
//
//  UIViewControllerC.swift
//  代码创建导航
//
//  Created by zhang on 16/1/16.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class UIViewControllerC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "第三个控制器"
        // 这只 item titleview
        self.navigationItem.titleView = UIImageView(image: UIImage(imageLiteral: "1"))
        // Do any additional setup after loading the view.
    }
    @IBAction func back(sender: AnyObject) {
        // 回到上一个控制器
        self.navigationController?.popViewControllerAnimated(true)
    }

    @IBAction func backRoot(sender: AnyObject) {
        // 回到根控制器
        self.navigationController?.popToRootViewControllerAnimated(true)
    }
}

自定义UIWindow

//
//  AppDelegate.swift
//  UIWindow
//
//  Created by zhang on 16/1/16.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        //已经在项目去掉了默认启动的 storyboard
        //初始化 UIWindow
        let window = UIWindow()
        //设置大小颜色,方便看效果
        window.bounds = UIScreen.mainScreen().bounds
        window.backgroundColor = UIColor.grayColor()
        //初始化控制器
        let controller = TestViewController()
        //设置window对象的根控制器为当前创建的控制器,因为没有root控制器,所以会显示出window设置的背景色
        window.rootViewController = controller
        //这里的注释部分是设置根控制器的view,设置了之后就会显示这个view,白色的,这里是用代码创建的,当然也可以换成加载xib
//        let view = UIView()
//        view.frame = window.bounds
//        view.backgroundColor = UIColor.whiteColor()
//        
//        controller.view = view
        self.window = window
        //设置当前窗口位主窗口并可见
        self.window?.makeKeyAndVisible()
        // Override point for customization after application launch.
        return true
    }

    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}

UIApplication常用设置

//
//  ViewController.swift
//  ios程序启动
//
//  Created by zhang on 16/1/16.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        super.touchesBegan(touches, withEvent: event)
        let app = UIApplication.sharedApplication()
        //设置联网状态
        app.networkActivityIndicatorVisible = app.networkActivityIndicatorVisible ? false : true
        //设置图标消息数字,需要先获得权限
        let userSeting = UIUserNotificationSettings(forTypes: UIUserNotificationType.Badge, categories: nil)
        app.registerUserNotificationSettings(userSeting)
        //再设置数字
        app.applicationIconBadgeNumber = 10
        //打开网址
        app.openURL(NSURL(string: "http://baidu.com")!)
    }

}

UIDatePickerView和UIToolbar的使用

自定义的xib类
//
//  KeyboardToolBar.swift
//  datepicker
//
//  Created by zhang on 16/1/16.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit
//自定义协议,响应当前工具条的按钮点击事件
@objc protocol KeyboardToolBarDelagate
{
    optional func keyboardToolBarDownButtonClicked()
}
class KeyboardToolBar: UIToolbar {
    @IBOutlet weak var preButton: UIBarButtonItem!

    @IBOutlet weak var downButton: UIBarButtonItem!

    @IBAction func downClick(sender: UIBarButtonItem) {
        self.keyboardDelagate?.keyboardToolBarDownButtonClicked?()
    }
    weak var keyboardDelagate:KeyboardToolBarDelagate!
    //快速初始化
    class func instance()->KeyboardToolBar
    {
        //记载xib
        let toolBar = NSBundle.mainBundle().loadNibNamed("KeyboardToolBar", owner: nil, options: nil).last as! KeyboardToolBar
        return toolBar
    }

    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
    }
    */
}
在控制器中的调用
//
//  ViewController.swift
//  datepicker
//
//  Created by zhang on 16/1/16.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController,KeyboardToolBarDelagate {
    var datePicker:UIDatePicker!

    @IBOutlet weak var textField: UITextField!


    override func viewDidLoad() {
        super.viewDidLoad()
        //创建UIDatePickerView
        self.datePicker = UIDatePicker()
        //设置时间地区
        self.datePicker.locale = NSLocale(localeIdentifier: "zh")
        //设置时间显示模式
        self.datePicker.datePickerMode = UIDatePickerMode.Date
        //设置UITexField的键盘
        self.textField.inputView = self.datePicker
        //返回自定义的xib对象
        let keyBoardToolBar = KeyboardToolBar.instance()
        //设置自定义xib对象的代理
        keyBoardToolBar.keyboardDelagate = self
        //设置键盘附件
        self.textField.inputAccessoryView = keyBoardToolBar
//        self.codeKeyboard()

//        self.view.addSubview(toolBar)
        // Do any additional setup after loading the view, typically from a nib.
    }
    //代理方法,把在键盘区的日期放到UITextField中
    func keyboardToolBarDownButtonClicked() {
        //获得Date对象
        let date = self.datePicker.date
        //初始化 NSDateFormate 对象
        let dateFormat = NSDateFormatter()
        //设置 NSDateFormate 对象的格式
        dateFormat.dateFormat = "yyyy-MM-dd"
        //会的日期对象格式化成字符串的值
        self.textField.text = dateFormat.stringFromDate(date)
        //收回键盘
        self.view.endEditing(true)
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    //代码创建键盘 barTool
    func codeKeyboard()
    {
        //创建 对象
        let toolBar = UIToolbar()
        //获得宽度
        let toolBarW = UIScreen.mainScreen().bounds.size.width
        //设置 toolBar的宽高,不设置不能显示
        toolBar.bounds = CGRectMake(0, 0, toolBarW, 50)
        //添加工具栏按钮
        let preButtonItem = UIBarButtonItem(title: "上一页", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
        //添加间隔
        let fixButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil)
        fixButtonItem.width = 20
        //按纽
        let nextButtonItem = UIBarButtonItem(title: "下一页", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
        //添加间隔,注意这个和 fixButtonItem 的不同
        let flexiButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
        let downtButtonItem = UIBarButtonItem(title: "down", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
        //把控件放到工具条中
        toolBar.items = [preButtonItem,fixButtonItem,nextButtonItem,flexiButtonItem,downtButtonItem]
        // 把工具条设置成当前键盘 
        self.textField.inputAccessoryView = toolBar
    }

}

模仿qq好友列表

注意点:UIButton图片的几个不常用的属性

模型类
import UIKit
//好友模型类
class QQFriend: NSObject {
    var icon:NSString!//用户头像
    var intro:NSString!//签名
    var name:NSString!//名字
    var vip:NSNumber!//是否是vip
    //便捷构造器
    convenience init(dic:[String : AnyObject]) {
        self.init()
        //kvc用法
        self.setValuesForKeysWithDictionary(dic)
    }
}
import UIKit
//好友分组类
class QQFriendGroup: NSObject {
    var friends:[QQFriend] = []//存放qq好友对象数组
    var name:NSString!//分组名称
    var online:NSNumber!//分组在线人数
    var hideGroup:Bool = true//是否隐藏,默认是隐藏的
    //快速plist文件中初始化对象数组
    class func instanceWithFile()->[QQFriendGroup]
    {
        let path = NSBundle.mainBundle().pathForResource("friends", ofType: "plist")
        let data = NSArray(contentsOfFile: path!)
        var qqFriendGroups:[QQFriendGroup] = []
        for var i = 0;i < data!.count;i++
        {
            let qqFriendGroupTemp = QQFriendGroup(dic: data![i] as! NSDictionary)
            qqFriendGroups.append(qqFriendGroupTemp)
        }
        return qqFriendGroups
    }
    //快速实例化方法
    convenience init(dic:NSDictionary) {
        self.init()
        self.name = dic["name"] as! NSString
        self.online = dic["online"] as! NSNumber
        let friendsData = dic["friends"] as! NSArray
        for var i = 0;i < friendsData.count;i++
        {
            let qqFriend:QQFriend! = QQFriend(dic: friendsData[i] as! [String : AnyObject])
            self.friends.append(qqFriend)
        }
    }
}
自定义UITableView的Header类
//
//  QQFriendHeader.swift
//  QQFriend
//
//  Created by zhang on 16/1/10.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit
//自定义协议
@objc protocol QQFriendHeaderShowFriendButtonClick
{
    optional func QQFriendHeaderShowFriendButtonClicked(tag:Int)
}
//自定义header类,注意继承自 UITableViewHeaderFooterView
class QQFriendHeader: UITableViewHeaderFooterView {

    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
    }
    */
    weak var buttonView:UIButton!
    weak var lableView:UILabel!
    weak var qqFriendGroup:QQFriendGroup!
        {
        didSet
        {
            self.assignSubViewContent()
        }
    }
    weak var delegate:QQFriendHeaderShowFriendButtonClick!//代理参数
    //可重用Header
    class func instance(tableView:UITableView)->QQFriendHeader
    {
        let identifier = "QQFriendSectionHeader"
        var header:UITableViewHeaderFooterView! = tableView.dequeueReusableHeaderFooterViewWithIdentifier(identifier)
        if header == nil
        {
            header = QQFriendHeader(reuseIdentifier: identifier)
        }
        let temp = header as! QQFriendHeader
        return temp
    }
    //重写父类的构造方法,添加需要的子控件
    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)
        //自定义button,用于覆盖于view表层,响应点击时间
        let buttonView = UIButton(type: UIButtonType.Custom)
        buttonView.setImage(UIImage(imageLiteral: "buddy_header_arrow"), forState: UIControlState.Normal)
        buttonView.imageView?.contentMode = UIViewContentMode.Center//图片不压缩
        buttonView.imageView?.clipsToBounds = false//图片不裁剪
        buttonView.setBackgroundImage(UIImage(imageLiteral: "buddy_header_bg"), forState: UIControlState.Normal)//设置背景
        buttonView.setBackgroundImage(UIImage(imageLiteral: "buddy_header_bg_highlighted"), forState: UIControlState.Highlighted)
        buttonView.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left//设置内容堆对齐方式
        buttonView.contentEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0)//设置内容边距
        buttonView.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)//设置标题颜色
        buttonView.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0)//设置标题边距
        buttonView.addTarget(self, action: "buttonClick:", forControlEvents: UIControlEvents.TouchDown)//绑定点击事件
        self.buttonView = buttonView
        let lableView = UILabel()
        self.lableView = lableView
        //加入父控件
        self.contentView.addSubview(self.buttonView)
        self.contentView.addSubview(self.lableView)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //给子控件赋值
    func assignSubViewContent()
    {
        let rotation = CGFloat(self.qqFriendGroup.hideGroup ? 0 : M_PI_2)//设置图片旋转,不设置的话,会出现因为重用而产生的bug
        self.buttonView.imageView?.transform = CGAffineTransformMakeRotation(rotation)
        self.buttonView.setTitle(self.qqFriendGroup.name as String, forState: UIControlState.Normal)
        self.lableView.text = "\(self.qqFriendGroup.online)/\(self.qqFriendGroup.friends.count)"
    }
    //往headerView中添加子控件的时候会调用
    //当改变了headerView的frame会调用
    override func layoutSubviews() {
        super.layoutSubviews()
        self.buttonView.setTitle(self.qqFriendGroup.name as String, forState: UIControlState.Normal)
        buttonView.frame = self.bounds

        //根据文字来设置labl的rect,用boundingRectWithSize的话需要字串是 NSString 格式,而且需要填一些参数,第二种简便些
        //lableText.boundingRectWithSize(CGSize.init(width: CGFloat.max, height: CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFontOfSize()], context: nil)
        let lableSize = CGSizeMake((self.lableView?.textRectForBounds(CGRectMake(0, 0, CGFloat.max, CGFloat.max), limitedToNumberOfLines: 1).size.width)!, self.frame.size.height)

        lableView.frame = CGRectMake(self.frame.size.width - (lableSize.width + 10), 0, lableSize.width,lableSize.height)
    }
    //响应点击
    func buttonClick(sender:UIButton)
    {

        //缩放图片
        let rotation = CGFloat(self.qqFriendGroup.hideGroup ? M_PI_2 : 0)
        self.qqFriendGroup.hideGroup = self.qqFriendGroup.hideGroup ? false : true//修改显示状态
        UIView.animateWithDuration(0.5, animations: {
            sender.imageView?.transform = CGAffineTransformMakeRotation(rotation)
        })
        //注意这里调用的方式
        self.delegate?.QQFriendHeaderShowFriendButtonClicked?(self.tag)
    }
}
在controller中的调用

import UIKit //遵守了几个协议 class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,QQFriendHeaderShowFriendButtonClick { //懒加载好有分组 lazy var qqFriendGroups:[QQFriendGroup] = QQFriendGroup.instanceWithFile() @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.tableView.dataSource = self//指定数据源 self.tableView.delegate = self//指定代理 self.tableView.sectionHeaderHeight = 44//设置行高 // self.tableView.sectionFooterHeight = 0 // print(self.qqFriendGroups) // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //返回分组数量 func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.qqFriendGroups.count } //返回对应cell func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let identifier = "QQFriendCell" var cell:UITableViewCell! = tableView.dequeueReusableCellWithIdentifier(identifier) if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: identifier) } cell.textLabel?.text = self.qqFriendGroups[indexPath.section].friends[indexPath.row].name as String cell.detailTextLabel?.text = self.qqFriendGroups[indexPath.section].friends[indexPath.row].intro as String cell.imageView?.image = UIImage(imageLiteral: (self.qqFriendGroups[indexPath.section].friends[indexPath.row].icon as String)) return cell } //返回分组纪录条数 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //因为默认是要不显示cell的,所以这里根据,分组对象的属性做了下判断, if self.qqFriendGroups[section].hideGroup { return 0 } else { return self.qqFriendGroups[section].friends.count } } //返回分组头的标题 // func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { // return self.qqFriendGroups[section].name as? String // } //返回自定义的头 func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = QQFriendHeader.instance(tableView) header.qqFriendGroup = self.qqFriendGroups[section] header.delegate = self//设置代理 header.tag = section//用于之后点击cell传递值来锁定分组 return header } // func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { // return nil // } override func prefersStatusBarHidden() -> Bool { return true } //代理cell点击的方法 func QQFriendHeaderShowFriendButtonClicked(tag:Int) { let indexSet = NSIndexSet(index: tag) self.tableView.reloadSections(indexSet, withRowAnimation: UITableViewRowAnimation.Fade)//重新加载所点击的分组 } }