iOS8开发~Swift UI详解

一、概要

使用Swift来完成iOS的UI界面,其实现思想与OC实现几乎一致,只不过写法上有很大区别,个别控件较之前有较大改动。由于有纯代码强迫症,所以接下来创建一个纯代码动项目,然后在此基础上详细描述常用UI控件的Swift代码实现。


二、创建项目

首先创建一个新项目SwiftDemo,语言选择Swift,详情参考《 iOS8开发~Swift(一)入门》,然后打开项目plist文件,删除其中的Main storyboard file base name一行,其他内容不需要改动,程序会默认从AppDelegate.swift开始执行,但此时主window需要代码初始化,因为我们已经删除了storyboard,所以需要添加如下代码:

[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {  
  2.         // Override point for customization after application launch.  
  3.         self.window = UIWindow(frame: UIScreen.mainScreen().bounds)  
  4.         self.window!.backgroundColor = UIColor.whiteColor()  
  5.         self.window!.makeKeyAndVisible()  
  6.           
  7.         return true  
  8.     }  

现在程序应该可以运行了,不过什么内容都没有。


下面打算搭建一个很常见都项目框架,主window的rootviewController为一个

UITabBarController对象,UITabBarController对象作为容器,其有两个标签,每个标签的内容展示为一个

UINavigationController对象,UINavigationController对象的rootViewController为实际的用户界面,相信这个结构使用OC实现大家都很熟悉了,但使用Swift该怎么样实现呢,其实思想都是一样都,只不过写法有区别而已,下面详细讨论代码实现了。


三、UI实现详解


1、在应用程序启动函数中添加如下代码:其中 viewControllerA 和 viewControllerB是需新创建都两个视图控制器,具体实现参考《 iOS8开发~Swift(一)入门》

[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. var window: UIWindow?  
  2.     var tabBarController: UITabBarController?  
  3.   
  4.     func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {  
  5.         // Override point for customization after application launch.  
  6.         self.window = UIWindow(frame: UIScreen.mainScreen().bounds)  
  7.         self.window!.backgroundColor = UIColor.whiteColor()  
  8.           
  9.         var viewControllerA = ViewControllerA();  
  10.         viewControllerA.title = "基本UI"  
  11.           
  12.         var viewControllerB = ViewControllerB();  
  13.         viewControllerB.title = "其他"  
  14.           
  15.         self.tabBarController = UITabBarController()  
  16.         self.tabBarController!.delegate = self;  
  17.         self.tabBarController!.viewControllers = [  
  18.             UINavigationController(rootViewController: viewControllerA),  
  19.             UINavigationController(rootViewController: viewControllerB)  
  20.         ]  
  21.         self.tabBarController!.selectedIndex = 0;  
  22.           
  23.         self.window!.rootViewController = self.tabBarController  
  24.         self.window!.makeKeyAndVisible()  
  25.           
  26.         return true  
  27.     }  


这样,之前描述的项目框架就实现了。如果需要在UITabBarController的代理方法中做一些事情,可以实现其代理:

[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. @UIApplicationMain  
  2. class AppDelegate: UIResponder, UIApplicationDelegate, UITabBarControllerDelegate  

[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. //UITabBarControllerDelegate  
  2.     func tabBarController(tabBarController: UITabBarController!, didSelectViewController viewController: UIViewController!) {  
  3.           
  4.     }  


运行效果:



2、以ViewControllerA作为UI介绍导航页面,在其中实现一个表视图TableView,其数据源从读取一个plist文件获取:


新建立一个ViewControllerA,取消勾选Xib选项,创建后重写loadView方法,然后初始化一个表视图,主要代码如下:

[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import UIKit  
  2.   
  3. class ViewControllerA: UIViewController, UITableViewDelegate, UITableViewDataSource {  
  4.       
  5.     var list: NSArray?  
  6.     var tableView: UITableView?  
  7.       
  8.     override func loadView() {  
  9.         super.loadView()  
  10.     }  
  11.       
  12.     override func viewDidLoad() {  
  13.         super.viewDidLoad()  
  14.          
  15.         self.list = NSArray(contentsOfFile: NSBundle.mainBundle().pathForResource("BasicUI", ofType:"plist"))  
  16.         println(self.list)  
  17.           
  18.         self.tableView = UITableView(frame: self.view.frame, style:UITableViewStyle.Plain)  
  19.         self.tableView!.delegate = self  
  20.         self.tableView!.dataSource = self  
  21.         self.tableView!.registerClass(UITableViewCell.self, forCellReuseIdentifier"Cell")  
  22.         self.view?.addSubview(self.tableView)  
  23.           
  24.     }  
  25.       
  26.     func numberOfSectionsInTableView(tableView: UITableView!) -> Int {  
  27.         return 1;  
  28.     }  
  29.       
  30.     func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {  
  31.         return self.list!.count  
  32.     }  
  33.       
  34.     func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!  
  35.     {  
  36.         let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell!  
  37.         cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator  
  38.         cell.textLabel.text = self.list?.objectAtIndex(indexPath.row) as String  
  39.           
  40.         return cell  
  41.     }  
  42.       
  43.     // UITableViewDelegate Methods  
  44.     func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!)  
  45.     {  
  46.         self.tableView!.deselectRowAtIndexPath(indexPath, animatedtrue)  
  47.           
  48.         var itemString = self.list?.objectAtIndex(indexPath.row) as String  
  49.           
  50.         var viewController : UIViewController?  
  51.         if itemString == "UIView" {  
  52.             viewController = TheViewController()  
  53.         } //省略部分代码  
  54.         else {  
  55.             println("viewController is nil")  
  56.         }  
  57.           
  58.         viewController!.hidesBottomBarWhenPushed = true  
  59.         self.navigationController.pushViewController(viewController, animated:true)  
  60.     }  
  61.   
  62.     override func didReceiveMemoryWarning() {  
  63.         super.didReceiveMemoryWarning()  
  64.           
  65.         // Dispose of any resources that can be recreated.  
  66.     }  
  67. }  

实际运行效果



3、下面逐个介绍各个控件的实现


(1)UIView

[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import UIKit  
  2.   
  3. class TheView: UIView {  
  4.     override func drawRect(rect: CGRect) {  
  5.         UIColor.redColor().setFill();  
  6.         UIRectFill(CGRectMake(0100100100));  
  7.     }  
  8. }  
  9.   
  10. class TheViewController: UIViewController {  
  11.   
  12.     override func loadView() {  
  13.         let theView = TheView()  
  14.         theView.backgroundColor = UIColor.brownColor()  
  15.         theView.layer.cornerRadius = 3  
  16.         theView.layer.borderWidth = 5  
  17.         theView.layer.borderColor = UIColor.darkGrayColor().CGColor  
  18.           
  19.         self.view = theView;  
  20.     }  
  21.   
  22.     override func viewDidLoad() {  
  23.         super.viewDidLoad()  
  24.   
  25. //        添加手势  
  26.         let recognizer = UITapGestureRecognizer(target: self, action"tapAction:")  
  27.         recognizer.numberOfTapsRequired = 2;  
  28.         recognizer.numberOfTouchesRequired = 1;  
  29.         self.view.addGestureRecognizer(recognizer)  
  30.     }  
  31.       
  32.     func tapAction(sender: UIGestureRecognizer)  
  33.     {  
  34.         println("tapAction")  
  35.     }  
  36.       
  37.     override func didReceiveMemoryWarning() {  
  38.         super.didReceiveMemoryWarning()  
  39.         // Dispose of any resources that can be recreated.  
  40.     }  
  41. }  


其中涉及到视图手势添加,视图重会,修改Layer等实现,效果如图:



(2)UILabel

[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import UIKit  
  2.   
  3. class LabelViewController: UIViewController {  
  4.   
  5.     override func loadView() {  
  6.         super.loadView();  
  7.     }  
  8.   
  9.     override func viewDidLoad() {  
  10.         super.viewDidLoad()  
  11.   
  12.         var label = UILabel(frame: CGRectMake(0100self.view.bounds.size.width200))  
  13.         label.backgroundColor = UIColor.blackColor()  
  14.         label.textColor = UIColor.whiteColor()  
  15.         label.numberOfLines = 0  
  16.         label.lineBreakMode = NSLineBreakMode.ByWordWrapping  
  17.         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. "  
  18.         label.font = UIFont.italicSystemFontOfSize(20)  
  19.           
  20.         self.view.addSubview(label)  
  21.     }  
  22.   
  23.     override func didReceiveMemoryWarning() {  
  24.         super.didReceiveMemoryWarning()  
  25.         // Dispose of any resources that can be recreated.  
  26.     }  
  27. }  


效果如图:



(3)UIButton

[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import UIKit  
  2.   
  3. class ButtonViewController: UIViewController {  
  4.   
  5.     override func loadView() {  
  6.         super.loadView();  
  7.     }  
  8.       
  9.     override func viewDidLoad() {  
  10.         super.viewDidLoad()  
  11.   
  12.         // Do any additional setup after loading the view.  
  13.           
  14.         var button = UIButton.buttonWithType(UIButtonType.System) as UIButton  
  15.         button.frame = CGRect(x:100, y:200, width:100, height:100);  
  16.         button.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)  
  17.         button.setTitleColor(UIColor.greenColor(), forState:UIControlState.Selected)  
  18.         button.setTitle("Normal", forState:UIControlState.Normal)  
  19.         button.setTitle("Selected", forState:UIControlState.Selected)  
  20.         button.setBackgroundImage(UIImage(named: "image.png"), forState:UIControlState.Normal)  
  21.         button.tag = 1000;  
  22.         button.clipsToBounds = true;  
  23.         button.layer.cornerRadius = 5;  
  24.         button.addTarget(self, action:"buttonAction:", forControlEvents:UIControlEvents.TouchUpInside)  
  25.           
  26.         self.view.addSubview(button)  
  27.     }  
  28.       
  29.     func buttonAction(sender: UIButton) {  
  30.         println("buttonAction")  
  31.     }  
  32.   
  33.     override func didReceiveMemoryWarning() {  
  34.         super.didReceiveMemoryWarning()  
  35.         // Dispose of any resources that can be recreated.  
  36.     }  
  37. }  


运行效果:




(4)UIImageView 与 UIImage

[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import UIKit  
  2.   
  3. class ImageViewController: UIViewController {  
  4.   
  5.     override func loadView() {  
  6.         super.loadView();  
  7.     }  
  8.   
  9.     override func viewDidLoad() {  
  10.         super.viewDidLoad()  
  11.   
  12.         // Do any additional setup after loading the view.  
  13.           
  14.         var imageView = UIImageView(frame: CGRectMake(1001005050))  
  15.         imageView.backgroundColor = UIColor.whiteColor();  
  16.         imageView.animationImages = [  
  17.             UIImage(contentsOfFile: NSBundle.mainBundle().pathForResource("bird-01", ofType:"png")),  
  18.             UIImage(contentsOfFile: NSBundle.mainBundle().pathForResource("bird-02", ofType:"png")),  
  19.             UIImage(contentsOfFile: NSBundle.mainBundle().pathForResource("bird-03", ofType:"png")),  
  20.             UIImage(named: "bird-04.png")  
  21.         ]  
  22.         imageView.contentMode = UIViewContentMode.ScaleAspectFit  
  23.         imageView.animationDuration = 1;  
  24.         imageView.startAnimating()  
  25.           
  26.         self.view.addSubview(imageView)  
  27.     }  
  28.   
  29.     override func didReceiveMemoryWarning() {  
  30.         super.didReceiveMemoryWarning()  
  31.         // Dispose of any resources that can be recreated.  
  32.     }  
  33. }  

运行效果,这是一个图片动画:



(5)UITextField

[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import UIKit  
  2.   
  3. class TextFieldViewController: UIViewController, UITextFieldDelegate {  
  4.   
  5.     override func loadView() {  
  6.         super.loadView();  
  7.     }  
  8.   
  9.     override func viewDidLoad() {  
  10.         super.viewDidLoad()  
  11.           
  12.         NSNotificationCenter.defaultCenter().addObserver(self, selector"textFieldTextDidBeginEditingNotification:", name:UITextFieldTextDidBeginEditingNotification, object:nil)  
  13.           
  14.         var textField = UITextField(frame: CGRectMake(1010030040))  
  15.         textField.backgroundColor = UIColor.clearColor()  
  16.         textField.textColor = UIColor.blackColor()  
  17.         textField.placeholder = "请输入..."  
  18.         textField.borderStyle = UITextBorderStyle.RoundedRect  
  19.         textField.adjustsFontSizeToFitWidth = true  
  20.         textField.delegate = self  
  21.           
  22.         self.view.addSubview(textField)  
  23.     }  
  24.       
  25.     func textFieldTextDidBeginEditingNotification(sender: NSNotification!) {  
  26.           
  27.     }  
  28.       
  29. //    UITextFieldDelegate  
  30.     func textFieldShouldBeginEditing(textField: UITextField!) -> Bool {  
  31.         return true;  
  32.     }  
  33.       
  34.     func textFieldDidBeginEditing(textField: UITextField!) {  
  35.     }  
  36.       
  37.     func textFieldShouldEndEditing(textField: UITextField!) -> Bool {  
  38.         return true;  
  39.     }  
  40.       
  41.     func textFieldDidEndEditing(textField: UITextField!) {  
  42.     }  
  43.       
  44.     func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {  
  45.         return true;  
  46.     }  
  47.       
  48.     func textFieldShouldReturn(textField: UITextField!) -> Bool {  
  49.         return true;  
  50.     }  
  51.   
  52.     override func didReceiveMemoryWarning() {  
  53.         super.didReceiveMemoryWarning()  
  54.         // Dispose of any resources that can be recreated.  
  55.     }  
  56. }  

运行效果:



(6)UITextView


[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import UIKit  
  2.   
  3. class TextViewController: UIViewController, UITextViewDelegate {  
  4.   
  5.     override func loadView() {  
  6.         super.loadView();  
  7.     }  
  8.   
  9.     override func viewDidLoad() {  
  10.         super.viewDidLoad()  
  11.   
  12.         var textView = UITextView(frame:CGRectMake(10.0120.0300.0400.0))  
  13.         textView.backgroundColor = UIColor.blackColor()  
  14.         textView.textColor = UIColor.whiteColor()  
  15.         textView.editable = false  
  16.         textView.font = UIFont.boldSystemFontOfSize(30)  
  17.         textView.delegate = self;  
  18.         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. "  
  19.         self.view.addSubview(textView)  
  20.     }  
  21.       
  22.     func textViewShouldBeginEditing(textView: UITextView!) -> Bool {  
  23.         return true;  
  24.     }  
  25.       
  26.     func textViewShouldEndEditing(textView: UITextView!) -> Bool {  
  27.         return true;  
  28.     }  
  29.       
  30.     func textViewDidBeginEditing(textView: UITextView!) {  
  31.     }  
  32.       
  33.     func textViewDidEndEditing(textView: UITextView!) {  
  34.     }  
  35.       
  36.     func textView(textView: UITextView!, shouldChangeTextInRange range: NSRange, replacementText text: String!) -> Bool {  
  37.         return true;  
  38.     }  
  39.       
  40.     func textViewDidChange(textView: UITextView!) {  
  41.     }  
  42.       
  43.     func textViewDidChangeSelection(textView: UITextView!) {  
  44.     }  
  45.       
  46.     func textView(textView: UITextView!, shouldInteractWithURL URL: NSURL!, inRange characterRange: NSRange) -> Bool {  
  47.         return true;  
  48.     }  
  49.       
  50.     func textView(textView: UITextView!, shouldInteractWithTextAttachment textAttachment: NSTextAttachment!, inRange characterRange: NSRange) -> Bool {  
  51.         return true;  
  52.     }  
  53.   
  54.     override func didReceiveMemoryWarning() {  
  55.         super.didReceiveMemoryWarning()  
  56.         // Dispose of any resources that can be recreated.  
  57.     }  
  58.   
  59. }  

运行效果:



(7)UISwitch


[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import UIKit  
  2.   
  3. class SwitchViewController: UIViewController {  
  4.   
  5.     override func loadView() {  
  6.         super.loadView();  
  7.     }  
  8.   
  9.     override func viewDidLoad() {  
  10.         super.viewDidLoad()  
  11.   
  12.         var switchCtr = UISwitch(frame: CGRectMake(1001008030))  
  13.         switchCtr.on = true  
  14.         switchCtr.addTarget(self, action"switchAction:", forControlEvents:UIControlEvents.ValueChanged)  
  15.         self.view.addSubview(switchCtr)  
  16.     }  
  17.       
  18.     func switchAction(sender: UISwitch) {  
  19.         println("switchAction")  
  20.     }  
  21.   
  22.     override func didReceiveMemoryWarning() {  
  23.         super.didReceiveMemoryWarning()  
  24.         // Dispose of any resources that can be recreated.  
  25.     }  
  26.   
  27. }  

运行效果:



(8)UIScrollView

[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import UIKit  
  2.   
  3. class ScrollViewController: UIViewController, UIScrollViewDelegate {  
  4.   
  5.     override func loadView() {  
  6.         super.loadView();  
  7.     }  
  8.   
  9.     override func viewDidLoad() {  
  10.         super.viewDidLoad()  
  11.   
  12.         var scroll = UIScrollView(frame: self.view.bounds)  
  13.         scroll.pagingEnabled = true  
  14.         scroll.scrollEnabled = true  
  15.         scroll.showsVerticalScrollIndicator = true  
  16.         scroll.showsHorizontalScrollIndicator = true  
  17.         scroll.delegate = self  
  18.           
  19.         var X : CGFloat = 0  
  20.         for (var i = 0; i < 2; i++) {  
  21.             var label = UILabel()  
  22.             label.text = "\(i)"  
  23.             label.textAlignment = NSTextAlignment.Center  
  24.             label.backgroundColor = UIColor.lightGrayColor()  
  25.             label.frame = CGRectMake(X, 0self.view.bounds.size.widthself.view.bounds.size.height)  
  26.             X += 320  
  27.             scroll.addSubview(label)  
  28.         }  
  29.           
  30.         scroll.contentSize = CGSizeMake(22 * self.view.bounds.size.widthself.view.bounds.size.height)  
  31.           
  32.         self.view.addSubview(scroll)  
  33.     }  
  34.       
  35. //    UIScrollViewDelegate  
  36.     func scrollViewDidScroll(scrollView: UIScrollView!) {  
  37.         println("scrollViewDidScroll")  
  38.     }  
  39.       
  40.     func scrollViewWillBeginDragging(scrollView: UIScrollView!) {  
  41.     }  
  42.       
  43.     func scrollViewWillEndDragging(scrollView: UIScrollView!, withVelocity velocity: CGPoint, targetContentOffset: CMutablePointer<CGPoint>) {  
  44.     }  
  45.       
  46.     func scrollViewDidEndDragging(scrollView: UIScrollView!, willDecelerate decelerate: Bool) {  
  47.          
  48.     }  
  49.       
  50.     func scrollViewWillBeginDecelerating(scrollView: UIScrollView!) {  
  51.     }  
  52.       
  53.     func scrollViewDidEndDecelerating(scrollView: UIScrollView!) {  
  54.     }  
  55.   
  56.     override func didReceiveMemoryWarning() {  
  57.         super.didReceiveMemoryWarning()  
  58.         // Dispose of any resources that can be recreated.  
  59.     }  
  60.   
  61. }  

运行效果:



(9)UIPageView

[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import UIKit  
  2.   
  3. class PageControlViewController: UIViewController {  
  4.   
  5.     override func loadView() {  
  6.         super.loadView()  
  7.     }  
  8.   
  9.     override func viewDidLoad() {  
  10.         super.viewDidLoad()  
  11.   
  12.         var pageControl = UIPageControl(frame: CGRectMake(100100100100));  
  13.         pageControl.numberOfPages = 10  
  14.         pageControl.currentPage = 5  
  15.         pageControl.currentPageIndicatorTintColor = UIColor.grayColor()  
  16.         pageControl.pageIndicatorTintColor = UIColor.redColor()  
  17.         pageControl.addTarget(self, action"pageControlAction:", forControlEvents:UIControlEvents.ValueChanged)  
  18.           
  19.         self.view.addSubview(pageControl)  
  20.     }  
  21.       
  22.     func pageControlAction(sender: UIPageControl) {  
  23.         println("pageControlAction:\(sender.currentPage)")  
  24.     }  
  25.   
  26.     override func didReceiveMemoryWarning() {  
  27.         super.didReceiveMemoryWarning()  
  28.         // Dispose of any resources that can be recreated.  
  29.     }  
  30. }  

效果如图:



(10)UIAlertView 与 UIActionSheet

[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import UIKit  
  2.   
  3. class AlertViewController: UIViewController {  
  4.   
  5.     override func loadView() {  
  6.         super.loadView()  
  7.     }  
  8.       
  9.     override func viewDidAppear(animated: Bool) {  
  10.           
  11.         let alertController = UIAlertController(title: "title", message"message", preferredStyle: UIAlertControllerStyle.Alert)  
  12.           
  13. //        let alertController = UIAlertController(title: "title", message: "message", preferredStyle: UIAlertControllerStyle.ActionSheet)  
  14.           
  15.         let cancelAction = UIAlertAction(title: "cancel", style: UIAlertActionStyle.Cancel) { action in  
  16.             println("cancel")  
  17.         }  
  18.           
  19.         let otherAction = UIAlertAction(title: "other", style: UIAlertActionStyle.Default) { action in  
  20.             NSLog("other")  
  21.         }  
  22.           
  23.         let secondAction = UIAlertAction(title: "secondAction", style: UIAlertActionStyle.Default) { action in  
  24.             NSLog("secondAction")  
  25.         }  
  26.           
  27.         alertController.addAction(cancelAction)  
  28.         alertController.addAction(otherAction)  
  29.         alertController.addAction(secondAction)  
  30.           
  31.         presentViewController(alertController, animatedtrue, completion: nil)  
  32.     }  
  33.   
  34.     override func viewDidLoad() {  
  35.         super.viewDidLoad()  
  36.           
  37.           
  38.     }  
  39.   
  40.     override func didReceiveMemoryWarning() {  
  41.         super.didReceiveMemoryWarning()  
  42.         // Dispose of any resources that can be recreated.  
  43.     }  
  44. }  


运行效果:

     



(11)UIActivityIndicatorView


[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import UIKit  
  2.   
  3. class ActivityIndicatorViewController: UIViewController {  
  4.   
  5.     override func loadView() {  
  6.         super.loadView()  
  7.     }  
  8.       
  9.     override func viewDidAppear(animated: Bool) {  
  10.           
  11.         var activity = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)  
  12.         activity.frame = CGRectMake(1001004040)  
  13.         activity.startAnimating()  
  14.         activity.hidesWhenStopped = true  
  15.           
  16.         self.view.addSubview(activity)  
  17.     }  
  18.   
  19.     override func viewDidLoad() {  
  20.         super.viewDidLoad()  
  21.     }  
  22.   
  23.     override func didReceiveMemoryWarning() {  
  24.         super.didReceiveMemoryWarning()  
  25.         // Dispose of any resources that can be recreated.  
  26.     }  
  27.       
  28. }  


运行效果:



(12)UISlider


[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import UIKit  
  2.   
  3. class SliderViewController: UIViewController {  
  4.   
  5.     override func loadView() {  
  6.         super.loadView()  
  7.     }  
  8.   
  9.     override func viewDidLoad() {  
  10.         super.viewDidLoad()  
  11.   
  12.         var slider = UISlider(frame:CGRectMake(10.0150.0300.030.0))  
  13.         slider.addTarget(self, action:"sliderAction:", forControlEvents:UIControlEvents.ValueChanged)  
  14.         self.view.addSubview(slider)  
  15.     }  
  16.       
  17.     func sliderAction(sender: UISlider) {  
  18.         println("sliderAction:\(sender.value)")  
  19.     }  
  20.   
  21.     override func didReceiveMemoryWarning() {  
  22.         super.didReceiveMemoryWarning()  
  23.         // Dispose of any resources that can be recreated.  
  24.     }  
  25. }  


运行效果:



(13)UIProgressView


[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import UIKit  
  2.   
  3. class ProgressViewController: UIViewController {  
  4.   
  5.     override func loadView() {  
  6.         super.loadView()  
  7.     }  
  8.       
  9.     override func viewDidAppear(animated: Bool) {  
  10.         var progress = UIProgressView(progressViewStyle:UIProgressViewStyle.Default)  
  11.         progress.progressTintColor = UIColor.blackColor()  
  12.         progress.trackTintColor  = UIColor.redColor()  
  13.         progress.frame = CGRectMake(10.0150.0300.040.0)  
  14.         progress.setProgress(0.9, animatedtrue)  
  15.         self.view.addSubview(progress)  
  16.     }  
  17.   
  18.     override func viewDidLoad() {  
  19.         super.viewDidLoad()  
  20.     }  
  21.   
  22.     override func didReceiveMemoryWarning() {  
  23.         super.didReceiveMemoryWarning()  
  24.         // Dispose of any resources that can be recreated.  
  25.     }  
  26. }  


效果如图:



(14)UISegmentedControl


[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import UIKit  
  2.   
  3. class SegmentedViewController: UIViewController {  
  4.   
  5.     override func loadView() {  
  6.         super.loadView()  
  7.     }  
  8.   
  9.     override func viewDidLoad() {  
  10.         super.viewDidLoad()  
  11.   
  12.         var segment = UISegmentedControl(items:["one""two""three""four"])  
  13.         segment.frame = CGRectMake(10.0110.0300.030.0)  
  14.         segment.segmentedControlStyle = UISegmentedControlStyle.Bordered  
  15.         segment.momentary = true  
  16.         segment.addTarget(self, action:"segmentAction:", forControlEvents:UIControlEvents.TouchUpInside)  
  17.           
  18.         self.view.addSubview(segment)  
  19.     }  
  20.       
  21.     func segmentAction(sender: UISegmentedControl) {  
  22.         println("segmentAction")  
  23.     }  
  24.   
  25.     override func didReceiveMemoryWarning() {  
  26.         super.didReceiveMemoryWarning()  
  27.         // Dispose of any resources that can be recreated.  
  28.     }  
  29.   
  30. }  


实现效果:



(15)UIDatePicker


[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import UIKit  
  2.   
  3. class DatePickerViewController: UIViewController {  
  4.   
  5.     override func loadView() {  
  6.         super.loadView()  
  7.     }  
  8.   
  9.     override func viewDidLoad() {  
  10.         super.viewDidLoad()  
  11.           
  12.         var datePicker = UIDatePicker(frame:CGRectMake(0.0120.0200.0200.0))  
  13.         datePicker.datePickerMode = UIDatePickerMode.DateAndTime  
  14.         datePicker.minimumDate = NSDate.date()  
  15.         datePicker.minuteInterval = 1  
  16.         datePicker.addTarget(self, action"action", forControlEvents: UIControlEvents.ValueChanged)  
  17.           
  18.         self.view.addSubview(datePicker)  
  19.     }  
  20.       
  21.     func action() {  
  22.         println("action")  
  23.     }  
  24.   
  25.     override func didReceiveMemoryWarning() {  
  26.         super.didReceiveMemoryWarning()  
  27.         // Dispose of any resources that can be recreated.  
  28.     }  
  29.   
  30. }  


实现效果:



(16)UIWebView

[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import UIKit  
  2.   
  3. class WebViewController: UIViewController, UIWebViewDelegate {  
  4.   
  5.     override func loadView() {  
  6.         super.loadView()  
  7.     }  
  8.   
  9.     override func viewDidLoad() {  
  10.         super.viewDidLoad()  
  11.   
  12.         var webView = UIWebView(frame: self.view.bounds)  
  13.         webView.backgroundColor = UIColor.whiteColor()  
  14.         webView.scalesPageToFit = true  
  15.         webView.delegate = self;  
  16.           
  17.         var url = NSURL(string: "http://www.baidu.com")  
  18.         var request = NSURLRequest(URL: url)  
  19.           
  20.         webView.loadRequest(request)  
  21.           
  22.         self.view.addSubview(webView)  
  23.     }  
  24.       
  25. //    UIWebViewDelegate  
  26.     func webViewDidStartLoad(webView: UIWebView) {  
  27.         UIApplication.sharedApplication().networkActivityIndicatorVisible = true  
  28.     }  
  29.       
  30.     func webViewDidFinishLoad(webView: UIWebView) {  
  31.         UIApplication.sharedApplication().networkActivityIndicatorVisible = false  
  32.     }  
  33.       
  34.     func webView(webView: UIWebView, didFailLoadWithError error: NSError) {  
  35.         println("didFailLoadWithError")  
  36.         UIApplication.sharedApplication().networkActivityIndicatorVisible = false  
  37.     }  
  38.   
  39.     func textFieldShouldReturn(textField: UITextField) -> Bool {  
  40.         textField.resignFirstResponder()  
  41.         return true  
  42.     }  
  43.   
  44.     override func didReceiveMemoryWarning() {  
  45.         super.didReceiveMemoryWarning()  
  46.         // Dispose of any resources that can be recreated.  
  47.     }  
  48. }  


实现效果:



(17)UIToolbar


[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import UIKit  
  2.   
  3. class ToolbarViewController: UIViewController {  
  4.   
  5.     override func loadView() {  
  6.         super.loadView()  
  7.     }  
  8.   
  9.     override func viewDidLoad() {  
  10.         super.viewDidLoad()  
  11.   
  12.         var toolBar = UIToolbar(frame:CGRectMake(10.0120.0300.030.0))  
  13.         toolBar.barStyle = .BlackTranslucent  
  14.         toolBar.tintColor = UIColor.greenColor()  
  15.         toolBar.backgroundColor = UIColor.blueColor()  
  16.           
  17.         var flexibleSpace = UIBarButtonItem(barButtonSystemItem:UIBarButtonSystemItem.FlexibleSpace, target:"barButtonItemClicked:", action:nil)  
  18.         var barBtnItemA = UIBarButtonItem(title: "one", style:UIBarButtonItemStyle.Plain, target:self, action:"barButtonItemClicked:")  
  19.         var barBtnItemB = UIBarButtonItem(title: "two", style:UIBarButtonItemStyle.Plain, target:self, action:"barButtonItemClicked:")  
  20.         var barBtnItemC = UIBarButtonItem(title: "three", style:UIBarButtonItemStyle.Plain, target:self, action:"barButtonItemClicked:")  
  21.         var barBtnItemD = UIBarButtonItem(title: "four", style:UIBarButtonItemStyle.Plain, target:self, action:"barButtonItemClicked:")  
  22.           
  23.         toolBar.items = [flexibleSpace, barBtnItemA, flexibleSpace, barBtnItemB, flexibleSpace, barBtnItemC, flexibleSpace, barBtnItemD, flexibleSpace]  
  24.           
  25.         self.view.addSubview(toolBar)  
  26.     }  
  27.       
  28.     func barButtonItemClicked(sender: UIBarButtonItem) {  
  29.         NSLog("barButtonItemClicked: \(sender)")  
  30.     }  
  31.   
  32.     override func didReceiveMemoryWarning() {  
  33.         super.didReceiveMemoryWarning()  
  34.         // Dispose of any resources that can be recreated.  
  35.     }  
  36. }  


实现效果:



(18)UISearchBar


[objc]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. import UIKit  
  2.   
  3. class SearchBarViewController: UIViewController, UISearchBarDelegate {  
  4.   
  5.     override func loadView() {  
  6.         super.loadView()  
  7.     }  
  8.       
  9.     override func viewDidLoad() {  
  10.         super.viewDidLoad()  
  11.   
  12.         var searchBar = UISearchBar(frame:CGRectMake(060.0320.0100.0))  
  13.         searchBar.showsCancelButton = true  
  14.         searchBar.searchBarStyle = UISearchBarStyle.Default  
  15.         searchBar.showsScopeBar = true  
  16.         searchBar.scopeButtonTitles = [  
  17.             "scope A",  
  18.             "scope B"  
  19.         ]  
  20.           
  21.         self.view.addSubview(searchBar)  
  22.     }  
  23.   
  24.     override func didReceiveMemoryWarning() {  
  25.         super.didReceiveMemoryWarning()  
  26.         // Dispose of any resources that can be recreated.  
  27.     }  
  28.       
  29. //    UISearchBarDelegate  
  30.     func searchBar(UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {  
  31.         println("selectedScopeButtonIndexDidChange \(selectedScope)")  
  32.     }  
  33.       
  34.     func searchBarSearchButtonClicked(searchBar: UISearchBar) {  
  35.         println("searchBarSearchButtonClicked: \(searchBar.text)")  
  36.           
  37.         searchBar.resignFirstResponder()  
  38.     }  
  39.       
  40.     func searchBarCancelButtonClicked(searchBar: UISearchBar) {  
  41.         println("searchBarCancelButtonClicked")  
  42.         searchBar.resignFirstResponder()  
  43.     }  
  44.   
  45. }  


实现效果:




到这里基本常用到UI控件实现的Swift版本就搞定啦,当然实际项目中需要更灵活、更复杂的实现,这些代码仅供参考,希望有抛砖引玉的效果!更多内容请点击这里

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

欢迎加入群共同学习和进步:QQ群:170549973

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值