1. 程式人生 > >iOS8開發~Swift(三)UI詳解

iOS8開發~Swift(三)UI詳解

一、概要

使用Swift來完成iOS的UI介面,其實現思想與OC實現幾乎一致,只不過寫法上有很大區別,個別控制元件較之前有較大改動。由於有純程式碼強迫症,所以接下來建立一個純程式碼動專案,然後在此基礎上詳細描述常用UI控制元件的Swift程式碼實現。

二、建立專案

首先建立一個新專案SwiftDemo,語言選擇Swift,詳情參考iOS8開發~Swift(一)入門,然後開啟專案plist檔案,刪除其中的Main storyboard file base name一行,其他內容不需要改動,程式會預設從AppDelegate.swift開始執行,但此時主window需要程式碼初始化,因為我們已經刪除了storyboard,所以需要新增如下程式碼:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
        // Override point for customization after application launch.
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
        self.window!.backgroundColor = UIColor.whiteColor()
        self.window!.makeKeyAndVisible()
        
        return true
    }

現在程式應該可以運行了,不過什麼內容都沒有。

下面打算搭建一個很常見都專案框架,主window的rootviewController為一個

UITabBarController物件,UITabBarController物件作為容器,其有兩個標籤,每個標籤的內容展示為一個

UINavigationController物件,UINavigationController物件的rootViewController為實際的使用者介面,相信這個結構使用OC實現大家都很熟悉了,但使用Swift該怎麼樣實現呢,其實思想都是一樣都,只不過寫法有區別而已,下面詳細討論程式碼實現了。

三、UI實現詳解

1、在應用程式啟動函式中新增如下程式碼:其中 viewControllerA 和 viewControllerB是需新建立都兩個檢視控制器,具體實現參考

《 iOS8開發~Swift(一)入門》

var window: UIWindow?
    var tabBarController: UITabBarController?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
        // Override point for customization after application launch.
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
        self.window!.backgroundColor = UIColor.whiteColor()
        
        var viewControllerA = ViewControllerA();
        viewControllerA.title = "基本UI"
        
        var viewControllerB = ViewControllerB();
        viewControllerB.title = "其他"
        
        self.tabBarController = UITabBarController()
        self.tabBarController!.delegate = self;
        self.tabBarController!.viewControllers = [
            UINavigationController(rootViewController: viewControllerA),
            UINavigationController(rootViewController: viewControllerB)
        ]
        self.tabBarController!.selectedIndex = 0;
        
        self.window!.rootViewController = self.tabBarController
        self.window!.makeKeyAndVisible()
        
        return true
    }


這樣,之前描述的專案框架就實現了。如果需要在UITabBarController的代理方法中做一些事情,可以實現其代理:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UITabBarControllerDelegate

//UITabBarControllerDelegate
    func tabBarController(tabBarController: UITabBarController!, didSelectViewController viewController: UIViewController!) {
        
    }


執行效果:


2、以ViewControllerA作為UI介紹導航頁面,在其中實現一個表檢視TableView,其資料來源從讀取一個plist檔案獲取:

新建立一個ViewControllerA,取消勾選Xib選項,建立後重寫loadView方法,然後初始化一個表檢視,主要程式碼如下:

import UIKit

class ViewControllerA: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    var list: NSArray?
    var tableView: UITableView?
    
    override func loadView() {
        super.loadView()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
       
        self.list = NSArray(contentsOfFile: NSBundle.mainBundle().pathForResource("BasicUI", ofType:"plist"))
        println(self.list)
        
        self.tableView = UITableView(frame: self.view.frame, style:UITableViewStyle.Plain)
        self.tableView!.delegate = self
        self.tableView!.dataSource = self
        self.tableView!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        self.view?.addSubview(self.tableView)
        
    }
    
    func numberOfSectionsInTableView(tableView: UITableView!) -> Int {
        return 1;
    }
    
    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
        return self.list!.count
    }
    
    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
    {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell!
        cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
        cell.textLabel.text = self.list?.objectAtIndex(indexPath.row) as String
        
        return cell
    }
    
    // UITableViewDelegate Methods
    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!)
    {
        self.tableView!.deselectRowAtIndexPath(indexPath, animated: true)
        
        var itemString = self.list?.objectAtIndex(indexPath.row) as String
        
        var viewController : UIViewController?
        if itemString == "UIView" {
            viewController = TheViewController()
        } //省略部分程式碼
        else {
            println("viewController is nil")
        }
        
        viewController!.hidesBottomBarWhenPushed = true
        self.navigationController.pushViewController(viewController, animated:true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
        // Dispose of any resources that can be recreated.
    }
}

實際執行效果


3、下面逐個介紹各個控制元件的實現

(1)UIView

import UIKit

class TheView: UIView {
    override func drawRect(rect: CGRect) {
        UIColor.redColor().setFill();
        UIRectFill(CGRectMake(0, 100, 100, 100));
    }
}

class TheViewController: UIViewController {

    override func loadView() {
        let theView = TheView()
        theView.backgroundColor = UIColor.brownColor()
        theView.layer.cornerRadius = 3
        theView.layer.borderWidth = 5
        theView.layer.borderColor = UIColor.darkGrayColor().CGColor
        
        self.view = theView;
    }

    override func viewDidLoad() {
        super.viewDidLoad()

//        新增手勢
        let recognizer = UITapGestureRecognizer(target: self, action: "tapAction:")
        recognizer.numberOfTapsRequired = 2;
        recognizer.numberOfTouchesRequired = 1;
        self.view.addGestureRecognizer(recognizer)
    }
    
    func tapAction(sender: UIGestureRecognizer)
    {
        println("tapAction")
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}


其中涉及到檢視手勢新增,檢視重會,修改Layer等實現,效果如圖:


(2)UILabel

import UIKit

class LabelViewController: UIViewController {

    override func loadView() {
        super.loadView();
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        var label = UILabel(frame: CGRectMake(0, 100, self.view.bounds.size.width, 200))
        label.backgroundColor = UIColor.blackColor()
        label.textColor = UIColor.whiteColor()
        label.numberOfLines = 0
        label.lineBreakMode = NSLineBreakMode.ByWordWrapping
        label.text = "Swift is designed to provide seamless compatibility with Cocoa and Objective-C. You can use Objective-C APIs (ranging from system frameworks to your own custom code) in Swift, and you can use Swift APIs in Objective-C. "
        label.font = UIFont.italicSystemFontOfSize(20)
        
        self.view.addSubview(label)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}


效果如圖:


(3)UIButton

import UIKit

class ButtonViewController: UIViewController {

    override func loadView() {
        super.loadView();
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        var button = UIButton.buttonWithType(UIButtonType.System) as UIButton
        button.frame = CGRect(x:100, y:200, width:100, height:100);
        button.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
        button.setTitleColor(UIColor.greenColor(), forState:UIControlState.Selected)
        button.setTitle("Normal", forState:UIControlState.Normal)
        button.setTitle("Selected", forState:UIControlState.Selected)
        button.setBackgroundImage(UIImage(named: "image.png"), forState:UIControlState.Normal)
        button.tag = 1000;
        button.clipsToBounds = true;
        button.layer.cornerRadius = 5;
        button.addTarget(self, action:"buttonAction:", forControlEvents:UIControlEvents.TouchUpInside)
        
        self.view.addSubview(button)
    }
    
    func buttonAction(sender: UIButton) {
        println("buttonAction")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}


執行效果:


(4)UIImageView 與 UIImage

import UIKit

class ImageViewController: UIViewController {

    override func loadView() {
        super.loadView();
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        var imageView = UIImageView(frame: CGRectMake(100, 100, 50, 50))
        imageView.backgroundColor = UIColor.whiteColor();
        imageView.animationImages = [
            UIImage(contentsOfFile: NSBundle.mainBundle().pathForResource("bird-01", ofType:"png")),
            UIImage(contentsOfFile: NSBundle.mainBundle().pathForResource("bird-02", ofType:"png")),
            UIImage(contentsOfFile: NSBundle.mainBundle().pathForResource("bird-03", ofType:"png")),
            UIImage(named: "bird-04.png")
        ]
        imageView.contentMode = UIViewContentMode.ScaleAspectFit
        imageView.animationDuration = 1;
        imageView.startAnimating()
        
        self.view.addSubview(imageView)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

執行效果,這是一個圖片動畫:


(5)UITextField

import UIKit

class TextFieldViewController: UIViewController, UITextFieldDelegate {

    override func loadView() {
        super.loadView();
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldTextDidBeginEditingNotification:", name:UITextFieldTextDidBeginEditingNotification, object:nil)
        
        var textField = UITextField(frame: CGRectMake(10, 100, 300, 40))
        textField.backgroundColor = UIColor.clearColor()
        textField.textColor = UIColor.blackColor()
        textField.placeholder = "請輸入..."
        textField.borderStyle = UITextBorderStyle.RoundedRect
        textField.adjustsFontSizeToFitWidth = true
        textField.delegate = self
        
        self.view.addSubview(textField)
    }
    
    func textFieldTextDidBeginEditingNotification(sender: NSNotification!) {
        
    }
    
//    UITextFieldDelegate
    func textFieldShouldBeginEditing(textField: UITextField!) -> Bool {
        return true;
    }
    
    func textFieldDidBeginEditing(textField: UITextField!) {
    }
    
    func textFieldShouldEndEditing(textField: UITextField!) -> Bool {
        return true;
    }
    
    func textFieldDidEndEditing(textField: UITextField!) {
    }
    
    func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
        return true;
    }
    
    func textFieldShouldReturn(textField: UITextField!) -> Bool {
        return true;
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

執行效果:


(6)UITextView

import UIKit

class TextViewController: UIViewController, UITextViewDelegate {

    override func loadView() {
        super.loadView();
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        var textView = UITextView(frame:CGRectMake(10.0, 120.0, 300.0, 400.0))
        textView.backgroundColor = UIColor.blackColor()
        textView.textColor = UIColor.whiteColor()
        textView.editable = false
        textView.font = UIFont.boldSystemFontOfSize(30)
        textView.delegate = self;
        textView.text = "Swift is designed to provide seamless compatibility with Cocoa and Objective-C. You can use Objective-C APIs (ranging from system frameworks to your own custom code) in Swift, and you can use Swift APIs in Objective-C. "
        self.view.addSubview(textView)
    }
    
    func textViewShouldBeginEditing(textView: UITextView!) -> Bool {
        return true;
    }
    
    func textViewShouldEndEditing(textView: UITextView!) -> Bool {
        return true;
    }
    
    func textViewDidBeginEditing(textView: UITextView!) {
    }
    
    func textViewDidEndEditing(textView: UITextView!) {
    }
    
    func textView(textView: UITextView!, shouldChangeTextInRange range: NSRange, replacementText text: String!) -> Bool {
        return true;
    }
    
    func textViewDidChange(textView: UITextView!) {
    }
    
    func textViewDidChangeSelection(textView: UITextView!) {
    }
    
    func textView(textView: UITextView!, shouldInteractWithURL URL: NSURL!, inRange characterRange: NSRange) -> Bool {
        return true;
    }
    
    func textView(textView: UITextView!, shouldInteractWithTextAttachment textAttachment: NSTextAttachment!, inRange characterRange: NSRange) -> Bool {
        return true;
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

執行效果:


(7)UISwitch

import UIKit

class SwitchViewController: UIViewController {

    override func loadView() {
        super.loadView();
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        var switchCtr = UISwitch(frame: CGRectMake(100, 100, 80, 30))
        switchCtr.on = true
        switchCtr.addTarget(self, action: "switchAction:", forControlEvents:UIControlEvents.ValueChanged)
        self.view.addSubview(switchCtr)
    }
    
    func switchAction(sender: UISwitch) {
        println("switchAction")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

執行效果:


(8)UIScrollView

import UIKit

class ScrollViewController: UIViewController, UIScrollViewDelegate {

    override func loadView() {
        super.loadView();
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        var scroll = UIScrollView(frame: self.view.bounds)
        scroll.pagingEnabled = true
        scroll.scrollEnabled = true
        scroll.showsVerticalScrollIndicator = true
        scroll.showsHorizontalScrollIndicator = true
        scroll.delegate = self
        
        var X : CGFloat = 0
        for (var i = 0; i < 2; i++) {
            var label = UILabel()
            label.text = "\(i)"
            label.textAlignment = NSTextAlignment.Center
            label.backgroundColor = UIColor.lightGrayColor()
            label.frame = CGRectMake(X, 0, self.view.bounds.size.width, self.view.bounds.size.height)
            X += 320
            scroll.addSubview(label)
        }
        
        scroll.contentSize = CGSizeMake(2 * self.view.bounds.size.width, self.view.bounds.size.height)
        
        self.view.addSubview(scroll)
    }
    
//    UIScrollViewDelegate
    func scrollViewDidScroll(scrollView: UIScrollView!) {
        println("scrollViewDidScroll")
    }
    
    func scrollViewWillBeginDragging(scrollView: UIScrollView!) {
    }
    
    func scrollViewWillEndDragging(scrollView: UIScrollView!, withVelocity velocity: CGPoint, targetContentOffset: CMutablePointer<CGPoint>) {
    }
    
    func scrollViewDidEndDragging(scrollView: UIScrollView!, willDecelerate decelerate: Bool) {
       
    }
    
    func scrollViewWillBeginDecelerating(scrollView: UIScrollView!) {
    }
    
    func scrollViewDidEndDecelerating(scrollView: UIScrollView!) {
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

執行效果:


(9)UIPageView

import UIKit

class PageControlViewController: UIViewController {

    override func loadView() {
        super.loadView()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        var pageControl = UIPageControl(frame: CGRectMake(100, 100, 100, 100));
        pageControl.numberOfPages = 10
        pageControl.currentPage = 5
        pageControl.currentPageIndicatorTintColor = UIColor.grayColor()
        pageControl.pageIndicatorTintColor = UIColor.redColor()
        pageControl.addTarget(self, action: "pageControlAction:", forControlEvents:UIControlEvents.ValueChanged)
        
        self.view.addSubview(pageControl)
    }
    
    func pageControlAction(sender: UIPageControl) {
        println("pageControlAction:\(sender.currentPage)")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

效果如圖:


(10)UIAlertView 與 UIActionSheet

import UIKit

class AlertViewController: UIViewController {

    override func loadView() {
        super.loadView()
    }
    
    override func viewDidAppear(animated: Bool) {
        
        let alertController = UIAlertController(title: "title", message: "message", preferredStyle: UIAlertControllerStyle.Alert)
        
//        let alertController = UIAlertController(title: "title", message: "message", preferredStyle: UIAlertControllerStyle.ActionSheet)
        
        let cancelAction = UIAlertAction(title: "cancel", style: UIAlertActionStyle.Cancel) { action in
            println("cancel")
        }
        
        let otherAction = UIAlertAction(title: "other", style: UIAlertActionStyle.Default) { action in
            NSLog("other")
        }
        
        let secondAction = UIAlertAction(title: "secondAction", style: UIAlertActionStyle.Default) { action in
            NSLog("secondAction")
        }
        
        alertController.addAction(cancelAction)
        alertController.addAction(otherAction)
        alertController.addAction(secondAction)
        
        presentViewController(alertController, animated: true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}


執行效果:

     

(11)UIActivityIndicatorView

import UIKit

class ActivityIndicatorViewController: UIViewController {

    override func loadView() {
        super.loadView()
    }
    
    override func viewDidAppear(animated: Bool) {
        
        var activity = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
        activity.frame = CGRectMake(100, 100, 40, 40)
        activity.startAnimating()
        activity.hidesWhenStopped = true
        
        self.view.addSubview(activity)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}


執行效果:


(12)UISlider

import UIKit

class SliderViewController: UIViewController {

    override func loadView() {
        super.loadView()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        var slider = UISlider(frame:CGRectMake(10.0, 150.0, 300.0, 30.0))
        slider.addTarget(self, action:"sliderAction:", forControlEvents:UIControlEvents.ValueChanged)
        self.view.addSubview(slider)
    }
    
    func sliderAction(sender: UISlider) {
        println("sliderAction:\(sender.value)")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}


執行效果:


(13)UIProgressView

import UIKit

class ProgressViewController: UIViewController {

    override func loadView() {
        super.loadView()
    }
    
    override func viewDidAppear(animated: Bool) {
        var progress = UIProgressView(progressViewStyle:UIProgressViewStyle.Default)
        progress.progressTintColor = UIColor.blackColor()
        progress.trackTintColor  = UIColor.redColor()
        progress.frame = CGRectMake(10.0, 150.0, 300.0, 40.0)
        progress.setProgress(0.9, animated: true)
        self.view.addSubview(progress)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}


效果如圖:


(14)UISegmentedControl

import UIKit

class SegmentedViewController: UIViewController {

    override func loadView() {
        super.loadView()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        var segment = UISegmentedControl(items:["one", "two", "three", "four"])
        segment.frame = CGRectMake(10.0, 110.0, 300.0, 30.0)
        segment.segmentedControlStyle = UISegmentedControlStyle.Bordered
        segment.momentary = true
        segment.addTarget(self, action:"segmentAction:", forControlEvents:UIControlEvents.TouchUpInside)
        
        self.view.addSubview(segment)
    }
    
    func segmentAction(sender: UISegmentedControl) {
        println("segmentAction")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}


實現效果:


(15)UIDatePicker

import UIKit

class DatePickerViewController: UIViewController {

    override func loadView() {
        super.loadView()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        var datePicker = UIDatePicker(frame:CGRectMake(0.0, 120.0, 200.0, 200.0))
        datePicker.datePickerMode = UIDatePickerMode.DateAndTime
        datePicker.minimumDate = NSDate.date()
        datePicker.minuteInterval = 1
        datePicker.addTarget(self, action: "action", forControlEvents: UIControlEvents.ValueChanged)
        
        self.view.addSubview(datePicker)
    }
    
    func action() {
        println("action")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}


實現效果:


(16)UIWebView

import UIKit

class WebViewController: UIViewController, UIWebViewDelegate {

    override func loadView() {
        super.loadView()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        var webView = UIWebView(frame: self.view.bounds)
        webView.backgroundColor = UIColor.whiteColor()
        webView.scalesPageToFit = true
        webView.delegate = self;
        
        var url = NSURL(string: "http://www.baidu.com")
        var request = NSURLRequest(URL: url)
        
        webView.loadRequest(request)
        
        self.view.addSubview(webView)
    }
    
//    UIWebViewDelegate
    func webViewDidStartLoad(webView: UIWebView) {
        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        UIApplication.sharedApplication().networkActivityIndicatorVisible = false
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError) {
        println("didFailLoadWithError")
        UIApplication.sharedApplication().networkActivityIndicatorVisible = false
    }

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}


實現效果:


(17)UIToolbar

import UIKit

class ToolbarViewController: UIViewController {

    override func loadView() {
        super.loadView()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        var toolBar = UIToolbar(frame:CGRectMake(10.0, 120.0, 300.0, 30.0))
        toolBar.barStyle = .BlackTranslucent
        toolBar.tintColor = UIColor.greenColor()
        toolBar.backgroundColor = UIColor.blueColor()
        
        var flexibleSpace = UIBarButtonItem(barButtonSystemItem:UIBarButtonSystemItem.FlexibleSpace, target:"barButtonItemClicked:", action:nil)
        var barBtnItemA = UIBarButtonItem(title: "one", style:UIBarButtonItemStyle.Plain, target:self, action:"barButtonItemClicked:")
        var barBtnItemB = UIBarButtonItem(title: "two", style:UIBarButtonItemStyle.Plain, target:self, action:"barButtonItemClicked:")
        var barBtnItemC = UIBarButtonItem(title: "three", style:UIBarButtonItemStyle.Plain, target:self, action:"barButtonItemClicked:")
        var barBtnItemD = UIBarButtonItem(title: "four", style:UIBarButtonItemStyle.Plain, target:self, action:"barButtonItemClicked:")
        
        toolBar.items = [flexibleSpace, barBtnItemA, flexibleSpace, barBtnItemB, flexibleSpace, barBtnItemC, flexibleSpace, barBtnItemD, flexibleSpace]
        
        self.view.addSubview(toolBar)
    }
    
    func barButtonItemClicked(sender: UIBarButtonItem) {
        NSLog("barButtonItemClicked: \(sender)")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}


實現效果:


(18)UISearchBar

import UIKit

class SearchBarViewController: UIViewController, UISearchBarDelegate {

    override func loadView() {
        super.loadView()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        var searchBar = UISearchBar(frame:CGRectMake(0, 60.0, 320.0, 100.0))
        searchBar.showsCancelButton = true
        searchBar.searchBarStyle = UISearchBarStyle.Default
        searchBar.showsScopeBar = true
        searchBar.scopeButtonTitles = [
            "scope A",
            "scope B"
        ]
        
        self.view.addSubview(searchBar)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
//    UISearchBarDelegate
    func searchBar(UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
        println("selectedScopeButtonIndexDidChange \(selectedScope)")
    }
    
    func searchBarSearchButtonClicked(searchBar: UISearchBar) {
        println("searchBarSearchButtonClicked: \(searchBar.text)")
        
        searchBar.resignFirstResponder()
    }
    
    func searchBarCancelButtonClicked(searchBar: UISearchBar) {
        println("searchBarCancelButtonClicked")
        searchBar.resignFirstResponder()
    }

}


實現效果:


到這裡基本常用到UI控制元件實現的Swift版本就搞定啦,當然實際專案中需要更靈活、更復雜的實現,這些程式碼僅供參考,希望有拋磚引玉的效果!更多內容請點選這裡

Demo下載:http://download.csdn.net/detail/zfpp25_/7463851

歡迎加入群共同學習和進步:QQ群:170549973