iOS开发——Swift篇&教你玩转UI

Swift学习之常用UI的使用
最近笔者在开始学习苹果最新的编程语言,因为笔者认为,苹果既然出了这门语言就绝对不会放弃,除非苹果倒闭了(当然这里知识一个玩笑)。

所以在不久的将来,swift绝对是iOS 开发的主导语言,也许不会完全取代OC

 

笔者学完swift的语法之后就开始着手UI了,因为我觉得有着一定的OC基础。所以这里关于swift的语法就不做多介绍了,在后面的文章中,我将会详细介绍一下关于swift中的重点,难点语法和一些新特性。

下面是我在学习UI的时候自己总结的一些swift创建UI的代码,个人感觉和OC区别不到,但是还是有需要注意的地方。

 override func viewDidLoad()
    {
        self.view!.backgroundColor = UIColor.whiteColor()
            /**
            *  1******************** UILabel
            */

 1         if self.title == "UILabel"
 2         {
 3             var label = UILabel(frame: self.view.bounds)
 4 
 5   //这里也可以先创建再设置frame
 6             label.backgroundColor = UIColor.clearColor()
 7             label.textAlignment = NSTextAlignment.Center
 8             label.font = UIFont.systemFontOfSize(36)
 9             label.text = "Hello, Swift"
10             self.view.addSubview(label)
11         }

 


            /**
            *   2********************UIButton
            */

 1         else if self.title == "UIButton"
 2         {
 3             var button = UIButton.buttonWithType(UIButtonType.System) as? UIButton
 4             button!.frame = CGRectMake(110.0, 120.0, 100.0, 50.0)
 5             button!.backgroundColor = UIColor.grayColor()
 6             button?.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
 7             button!.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Highlighted)
 8             button?.setTitle("Touch Me", forState: UIControlState.Normal)
 9             button?.setTitle("Touch Me", forState: UIControlState.Highlighted)
10             button?.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
11             button!.tag = 100
12             self.view.addSubview(button!)
13         }

 


            /**
            *  3******************** UIImageView
            */
 

 1        else if self.title == "UIImageView"
 2         {
 3             var image     = UIImage(named: "swift-hero.png")
 4             var imageView = UIImageView(frame: CGRectMake((CGRectGetWidth(self.view.bounds) - image!.size.width) / 2.0, 120.0, image!.size.width, image!.size.height))
 5             imageView.image = image
 6             self.view.addSubview(imageView)
 7         }
 8 
 9         //当数量很多的时候我们使用swift中的心特性与法:闭包
10         image.animationImages = (1...10).map {
11         UIImage(named: "\($0)")
12         }

 


            /**
            *   4********************UISilder
            */

1         else if self.title == "UISlider"
2         {
3             var slider = UISlider(frame:CGRectMake(60.0, 120.0, 200.0, 30.0))
4             self.view.addSubview(slider)
5         }

 


            /**
            *  5******************** UIWebView
            */

 1         else if self.title == "UIWebView"
 2         {
 3             var webView = UIWebView(frame:self.view.bounds)
 4             var url = NSURL(string: "http://caipiao.m.taobao.com")
 5             var request = NSURLRequest(URL: url!)
 6             webView.loadRequest(request)
 7             self.view.addSubview(webView)
 8         }
 9 
10     *********
11 
12     //URL请求
13     func loadurl(url:String, web:UIWebView) {
14         
15         let aurl = NSURL(string: ("http://" + url))
16         let request = NSURLRequest(URL: aurl!)
17         web.loadRequest(request)
18     }
19     //网页开始载入
20     func webViewDidStartLoad(webView: UIWebView) {
21         progress.startAnimating()
22         UIApplication.sharedApplication().networkActivityIndicatorVisible = true
23     }
24     //网页载入结束
25     func webViewDidFinishLoad(webView: UIWebView) {
26         progress.stopAnimating()
27         UIApplication.sharedApplication().networkActivityIndicatorVisible = false
28     }
29     
30     override func didReceiveMemoryWarning() {
31         super.didReceiveMemoryWarning()
32         // Dispose of any resources that can be recreated.
33     }
34     //键盘退出
35     func textFieldShouldReturn(textField: UITextField) -> Bool {
36         //加载输入的网址
37         textField.resignFirstResponder()
38         //退出键盘
39         loadurl(text.text, web: web)
40         return true
41     }

 

*************
            /**
            *   6********************UISegmentedControl
            */

1         else if self.title == "UISegmentedControl"
2         {
3             var segmentControl = UISegmentedControl(items:["A", "B", "C", "D"])
4             segmentControl.frame = CGRectMake(110.0, 120.0, 100.0, 30.0)
5             self.view.addSubview(segmentControl)
6         }

 


            /**
            *   7********************UISwitch
            */

1         else if self.title == "UISwitch"
2         {
3             var switchControl = UISwitch(frame:CGRectMake(130.0, 120.0, 100.0, 30.0))
4             switchControl.on = true
5             self.view.addSubview(switchControl)
6         }

 


            /**
            *   8********************UItxetField
            */

1         else if self.title == "UITextField"
2         {
3             var textField = UITextField(frame:CGRectMake(60.0, 120.0, 200.0, 30.0))
4             textField.backgroundColor = UIColor.lightGrayColor()
5             textField.placeholder = "input text"
6             self.view.addSubview(textField)
7         }

 


            /**
            *   9********************UIScrollView
            */

 1         else if self.title == "UIScrollView"
 2         {
 3             var scrollView = UIScrollView(frame:CGRectMake(60.0, 120.0, 200.0, 200.0))
 4             scrollView.pagingEnabled = true
 5             scrollView.showsVerticalScrollIndicator = false
 6             self.view.addSubview(scrollView)
 7             
 8             var fX: CGFloat = 0.0
 9             for(var i = 0; i < 3; ++i)
10             {
11                 var view = UIView(frame:CGRectMake(fX, 0.0, 200.0, 200.0))
12                 fX += 200.0
13                 view.backgroundColor = UIColor.redColor()
14                 scrollView.addSubview(view)
15             }
16             scrollView.contentSize = CGSizeMake(3 * 200.0, 200.0)
17             self.view.addSubview(scrollView)
18         }

 


            /**
            *   10********************UISearchBar
            */

1         else if self.title == "UISearchBar"
2         {
3             var searchBar = UISearchBar(frame:CGRectMake(10.0, 120.0, 300.0, 30.0))
4             searchBar.showsCancelButton = true
5             searchBar.searchBarStyle = UISearchBarStyle.Minimal // Default, Prominent, Minimal
6 
7             self.view.addSubview(searchBar)
8         }

 


            /**
            *   11********************UIpageControl
            */

1         else if self.title == "UIPageControl"
2         {
3             // PageControl
4             var pageControl = UIPageControl(frame:CGRectMake(60.0, 120.0, 200.0, 200.0))
5             pageControl.numberOfPages = 5
6             pageControl.currentPageIndicatorTintColor = UIColor.blackColor()
7             pageControl.pageIndicatorTintColor = UIColor.redColor()
8             self.view.addSubview(pageControl)
9         }

 


            /**
            *   12********************UIDatePicker
            */

1         else if self.title == "UIDatePicker"
2         {
3             var datePicker = UIDatePicker(frame:CGRectMake(0.0, 120.0, 200.0, 200.0))
4             self.view.addSubview(datePicker)
5         }

 


            /**
            *  13******************** UIPickerView
            */

1         else if self.title == "UIPickerView"
2         {
3             var pickerView = UIPickerView(frame:CGRectMake(10.0, 120.0, 300.0, 200.0))
4             pickerView.delegate = self
5             pickerView.dataSource = self
6             self.view.addSubview(pickerView)
7         }

 


            /**
            *   14********************UIProgressView
            */

1         else if self.title == "UIProgressView"
2         {
3             var progressView = UIProgressView(progressViewStyle:UIProgressViewStyle.Default)
4             progressView.frame = CGRectMake(10.0, 120.0, 300.0, 30.0)
5             progressView.setProgress(0.8, animated: true)
6             self.view.addSubview(progressView)
7         }

 


            /**
            *  15******************** UITextView
            */

1         else if self.title == "UITextView"
2         {
3             var textView = UITextView(frame:CGRectMake(10.0, 120.0, 300.0, 200.0))
4             textView.backgroundColor = UIColor.lightGrayColor()
5             textView.editable = false
6             textView.font = UIFont.systemFontOfSize(20)
7             textView.text = "Swift is an innovative new programming language for Cocoa and Cocoa Touch. Writing code is interactive and fun, the syntax is concise yet expressive, and apps run lightning-fast. Swift is ready for your next iOS and OS X project — or for addition into your current app — because Swift code works side-by-side with Objective-C."
8             self.view.addSubview(textView)
9         }

 


            /**
            *   16********************UIToolbar
            */

 1         else if self.title == "UIToolbar"
 2         {
 3             var toolBar = UIToolbar(frame:CGRectMake(60.0, 120.0, 200.0, 30.0))
 4 
 5             var flexibleSpace = UIBarButtonItem(barButtonSystemItem:UIBarButtonSystemItem.FlexibleSpace, target:nil, action:nil)
 6             var barBtnItemA = UIBarButtonItem(title: "A", style:UIBarButtonItemStyle.Plain, target:nil, action:nil)
 7             var barBtnItemB = UIBarButtonItem(title: "B", style:UIBarButtonItemStyle.Plain, target:nil, action:nil)
 8             var barBtnItemC = UIBarButtonItem(title: "C", style:UIBarButtonItemStyle.Plain, target:nil, action:nil)
 9             var barBtnItemD = UIBarButtonItem(title: "D", style:UIBarButtonItemStyle.Plain, target:nil, action:nil)
10             
11             toolBar.items = [flexibleSpace, barBtnItemA, flexibleSpace, barBtnItemB, flexibleSpace, barBtnItemC, flexibleSpace, barBtnItemD, flexibleSpace]
12             self.view.addSubview(toolBar)
13         }

 


            /**
            *  16******************** UIActionSheet
            */

 1         else if self.title == "UIActionSheet"
 2         {
 3             // Button
 4             var button = UIButton.buttonWithType(UIButtonType.System) as? UIButton
 5             button!.frame = CGRectMake(60.0, 120.0, 200.0, 50.0)
 6             button!.backgroundColor = UIColor.grayColor()
 7             button?.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
 8             button!.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Highlighted)
 9             button?.setTitle("Show ActionSheet", forState: UIControlState.Normal)
10             button?.setTitle("Show ActionSheet", forState: UIControlState.Highlighted)
11             button?.addTarget(self, action: "showActionSheet", forControlEvents: UIControlEvents.TouchUpInside)
12             button!.tag = 101
13             self.view.addSubview(button!)
14         }

 


            /**
            *   17********************UIActivityIndicatorView
            */

 1         else if self.title == "UIActivityIndicatorView"
 2         {
 3             var activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle:UIActivityIndicatorViewStyle.Gray)
 4             activityIndicatorView.frame = CGRectMake(140.0, 120.0, 40.0, 40.0)
 5             activityIndicatorView.startAnimating()
 6             self.view.addSubview(activityIndicatorView)
 7         }
 8         else
 9         {}
10     }

 




下面是一些UI中对应按钮的target,和一些需要实现的方法:

    
    override func viewWillAppear(animated: Bool) {}
    override func viewDidAppear(animated: Bool) {}
    override func viewWillDisappear(animated: Bool) {}
    override func viewDidDisappear(animated: Bool) {}
    
    // Button Action
    func buttonAction(sender: UIButton)
    {
        var mathSum = MathSum()
        var sum = mathSum.sum(11, number2: 22)
        
        var alert = UIAlertController(title: "Title", message: String(format: "Result = %i", sum), preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
        self.presentViewController(alert, animated: true, completion: nil)
        
        /*
        var alertView = UIAlertView()
        alertView.title = "Title"
        alertView.message = "Message"
        alertView.addButtonWithTitle("OK")
        alertView.show()
        */

    }

// Button Handler
    // showActionSheet
    func showActionSheet()
    {
        var alertController = UIAlertController(title: "ActionSheet", message: "Message", preferredStyle: UIAlertControllerStyle.ActionSheet)
        alertController.addAction(UIAlertAction(title: "Go Back", style: UIAlertActionStyle.Destructive, handler: nil))
        self.presentViewController(alertController, animated: true, completion:nil)
    }
        // didReceiveMemoryWarning
    override func didReceiveMemoryWarning()
    {

  /********/

  }

后面的文章里,笔者将给大家打来使用swift开发项目的一些常用技术和区分swift与OC开发!

 
 
 
 

你可能感兴趣的:(swift)