swift常用UI控件的使用方法

对于习惯了OC代码的程序员来说,swift的语法简直让人不能忍受,今天将一些常用的UI控件简单做了一下整理。

import UIKit

class ViewController : UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.whiteColor()

        if self.title == "UILabel"
        {
            // Label
            let label = UILabel(frame: self.view.bounds)
            label.backgroundColor = UIColor.clearColor()
            label.textAlignment = NSTextAlignment.Center
            label.font = UIFont.systemFontOfSize(36)
            label.text = "Hello, Swift"
            self.view.addSubview(label)
        }
        else if self.title == "UIButton"
        {
            // Button
            let button = UIButton(type: UIButtonType.System)
            button.frame = CGRectMake(110, 120, 100, 50)
            button.backgroundColor = UIColor.grayColor()
            button.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
            button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Highlighted)
            button.setTitle("普通", forState: UIControlState.Normal)
            button.setTitle("高亮", forState: UIControlState.Highlighted)
            button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
            button.tag = 100
            self.view.addSubview(button)
        }
        else if self.title == "UIImageView"
        {
            let image     = UIImage(named: "swift-hero.png")
            let imageView = UIImageView(frame: CGRectMake((CGRectGetWidth(self.view.bounds) - image!.size.width) / 2.0, 120.0, image!.size.width, image!.size.height))
            imageView.image = image
            self.view.addSubview(imageView)
        }
        else if self.title == "UISlider"
        {
            let slider = UISlider(frame:CGRectMake(60, 120, 200, 30))
            self.view.addSubview(slider)
        }
        else if self.title == "UIWebView"
        {
            let webView = UIWebView(frame:self.view.bounds)
            let url = NSURL(string: "http://caipiao.m.taobao.com")
            let request = NSURLRequest(URL: url!)
            webView.loadRequest(request)
            self.view.addSubview(webView)
        }
        else if self.title == "UISegmentedControl"
        {
            let segmentControl = UISegmentedControl(items:["A", "B", "C", "D"])
            segmentControl.frame = CGRectMake(110, 120, 100, 30)
            self.view.addSubview(segmentControl)
        }
        else if self.title == "UISwitch"
        {
            let switchControl = UISwitch(frame:CGRectMake(130, 120, 100, 30))
            switchControl.on = true
            self.view.addSubview(switchControl)
        }
        else if self.title == "UITextField"
        {
            let textField = UITextField(frame:CGRectMake(60, 120, 200, 30))
            textField.backgroundColor = UIColor.lightGrayColor()
            textField.placeholder = "请输入"
            self.view.addSubview(textField)
        }
        else if self.title == "UIScrollView"
        {
            let scrollView = UIScrollView(frame:CGRectMake(60, 120, 200, 200))
            scrollView.pagingEnabled = true
            scrollView.showsVerticalScrollIndicator = false
            self.view.addSubview(scrollView)

            var fX: CGFloat = 0.0
            for(var i = 0; i < 3; ++i)
            {
                let view = UIView(frame:CGRectMake(fX, 0, 200, 200))
                fX += 200
                view.backgroundColor = UIColor(red: CGFloat(100 * i) / 256, green: CGFloat(100 * i) / 256, blue: CGFloat(100 * i) / 256, alpha: 1)
                // 这个地方因为swift对于类型的控制十分严格,颜色值采用的是CGFloat类型,但是i是int类型,所以需要强转
                scrollView.addSubview(view)
            }
            scrollView.contentSize = CGSizeMake(3 * 200, 0)
            self.view.addSubview(scrollView)
        }
        else if self.title == "UISearchBar"
        {
            let searchBar = UISearchBar(frame:CGRectMake(10.0, 120.0, 300.0, 30.0))
            searchBar.showsCancelButton = true
            searchBar.searchBarStyle = UISearchBarStyle.Minimal // Default, Prominent, Minimal

            self.view.addSubview(searchBar)
        }
        else if self.title == "UIPageControl"
        {
            // PageControl
            let pageControl = UIPageControl(frame:CGRectMake(60.0, 120.0, 200.0, 200.0))
            pageControl.numberOfPages = 5
            pageControl.currentPageIndicatorTintColor = UIColor.blackColor()
            pageControl.pageIndicatorTintColor = UIColor.redColor()
            self.view.addSubview(pageControl)
        }
        else if self.title == "UIDatePicker"
        {
            let datePicker = UIDatePicker(frame:CGRectMake(0.0, 120.0, 200.0, 200.0))
            self.view.addSubview(datePicker)
        }
        else if self.title == "UIPickerView"
        {
            let pickerView = UIPickerView(frame:CGRectMake(10.0, 120.0, 300.0, 200.0))
            pickerView.delegate = self
            pickerView.dataSource = self
            self.view.addSubview(pickerView)
        }
        else if self.title == "UIProgressView"
        {
            let progressView = UIProgressView(progressViewStyle:UIProgressViewStyle.Default)
            progressView.frame = CGRectMake(10.0, 120.0, 300.0, 30.0)
            progressView.setProgress(0.8, animated: true)
            self.view.addSubview(progressView)
        }
        else if self.title == "UITextView"
        {
            let textView = UITextView(frame:CGRectMake(10.0, 120.0, 300.0, 200.0))
            textView.backgroundColor = UIColor.lightGrayColor()
            textView.editable = false
            textView.font = UIFont.systemFontOfSize(20)
            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."
            self.view.addSubview(textView)
        }
        else if self.title == "UIToolbar"
        {
            let toolBar = UIToolbar(frame:CGRectMake(60.0, 120.0, 200.0, 30.0))

            let flexibleSpace = UIBarButtonItem(barButtonSystemItem:UIBarButtonSystemItem.FlexibleSpace, target:nil, action:nil)
            let barBtnItemA = UIBarButtonItem(title: "A", style:UIBarButtonItemStyle.Plain, target:nil, action:nil)
            let barBtnItemB = UIBarButtonItem(title: "B", style:UIBarButtonItemStyle.Plain, target:nil, action:nil)
            let barBtnItemC = UIBarButtonItem(title: "C", style:UIBarButtonItemStyle.Plain, target:nil, action:nil)
            let barBtnItemD = UIBarButtonItem(title: "D", style:UIBarButtonItemStyle.Plain, target:nil, action:nil)

            toolBar.items = [flexibleSpace, barBtnItemA, flexibleSpace, barBtnItemB, flexibleSpace, barBtnItemC, flexibleSpace, barBtnItemD, flexibleSpace]
            self.view.addSubview(toolBar)
        }
        else if self.title == "UIActionSheet"
        {
            // Button
            let button = UIButton(type: UIButtonType.System)
            button.frame = CGRectMake(60.0, 120.0, 200.0, 50.0)
            button.backgroundColor = UIColor.grayColor()
            button.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
            button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Highlighted)
            button.setTitle("ActionSheet", forState: UIControlState.Normal)
            button.setTitle("ActionSheet", forState: UIControlState.Highlighted)
            button.addTarget(self, action: "showActionSheet", forControlEvents: UIControlEvents.TouchUpInside)
            button.tag = 101
            self.view.addSubview(button)
        }
        else if self.title == "UIActivityIndicatorView"
        {
            let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle:UIActivityIndicatorViewStyle.Gray)
            activityIndicatorView.frame = CGRectMake(140.0, 120.0, 40.0, 40.0)
            activityIndicatorView.startAnimating()
            self.view.addSubview(activityIndicatorView)
        }
    }
    func buttonAction(sender: UIButton) {

        let alertController = UIAlertController(title: "通知", message: "确定还是取消", preferredStyle: UIAlertControllerStyle.Alert)

        let alertView1 = UIAlertAction(title: "确定", style: UIAlertActionStyle.Default) { (UIAlertAction) -> Void in
            print("确定按钮点击事件")
        }
        let alertView2 = UIAlertAction(title: "取消", style: UIAlertActionStyle.Default) { (UIAlertAction) -> Void in
            print("取消按钮点击事件")
        }
        let alertView3 = UIAlertAction(title: "下次吧", style: UIAlertActionStyle.Default) { (UIAlertAction) -> Void in
            print("下次吧按钮点击事件")
        }
        alertController.addAction(alertView1)
        alertController.addAction(alertView2)
        alertController.addAction(alertView3)
        self.presentViewController(alertController, animated: true, completion: nil)
    }

    func showActionSheet()
    {
        let alertController = UIAlertController(title: "通知", message: "确定还是取消", preferredStyle: UIAlertControllerStyle.ActionSheet)

        let alertView1 = UIAlertAction(title: "确定", style: UIAlertActionStyle.Default) { (UIAlertAction) -> Void in
            print("确定按钮点击事件")
        }
        let alertView2 = UIAlertAction(title: "取消", style: UIAlertActionStyle.Default) { (UIAlertAction) -> Void in
            print("取消按钮点击事件")
        }
        let alertView3 = UIAlertAction(title: "下次吧", style: UIAlertActionStyle.Default) { (UIAlertAction) -> Void in
            print("下次吧按钮点击事件")
        }
        alertController.addAction(alertView1)
        alertController.addAction(alertView2)
        alertController.addAction(alertView3)
        self.presentViewController(alertController, animated: true, completion: nil)

    }

    // UIPickerViewDataSource Methods
    // returns the number of ‘columns‘ to display.
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int
    {
        return 3
    }

    // returns the # of rows in each component..
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
    {
        return 10
    }

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
    {
        return String(format:"%i", row)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
时间: 2024-10-18 17:13:36

swift常用UI控件的使用方法的相关文章

android_常用UI控件_01_TextView3_点击打开新的activity

点击textview打开新的activity (1) MainActivity.java package com.example.android_textview_opennewactivity; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.text.SpannableString; import android.text.Spanned;

android_常用UI控件_01_TextView4_rollingsubtitles效果加链接文字

(1)Mainactivity.java package com.example.android_textview_rollingsubtitles; import java.sql.Wrapper; import android.os.Bundle; import android.app.Activity; import android.text.Html; import android.text.TextUtils; import android.text.TextUtils.Truncat

android_常用UI控件_01_TextView2

显示图片和文字 MainActivity.java package com.example.android_textview_showqqface; import java.lang.reflect.Field; import android.os.Bundle; import android.app.Activity; import android.graphics.Color; import android.graphics.drawable.Drawable; import android

IOS开发UI篇--常用UI控件的基本使用

一. UIButton概述: UIKit框架提供了非常多的UI控件,其中有些控件天天使用,比如UIButton.UILabel.UIImageView.UITableView等. UIButton,俗称“按钮”,通常点击某个控件后,会做出相应反应的都是按钮.按钮的功能较多,既能显示图片又能显示汉字还能随时调整图片的文字和位置,如下面两个图 团购和音乐播放器的app: 下面本文通过一个实例总结一下它们的基本使用. 二. 按钮的基本设置 按钮既可以通过mainstoryboard创建也可以通过代码创

创建自注册的Swift UI 控件

原文链接 : Swift Programming 101: Creating Self-Registering Swift UI Controls 原文作者 : Kevin McNeish 译文出自 : 开发技术前线 www.devtf.cn 译者 : kmyhy 校对者:LastDay 状态:完成 对于自定义控件来说,在不破坏原有的消息机制的前提下,如何响应事件通知?在本文中,我将演示一个通知代理类,通过一个简单的例子,我们用该类向已有的iOS UI控件中增加了自己的新功能:为Text Vie

Atitit.swt&#160;线程调用ui控件的方法

Atitit.swt 线程调用ui控件的方法 1 SwingUtilities.invokeLater1 2 display.asyncExec方法1 3  display.timerExec(500,timer);2 4 .但有时候并不一定要程序执行时就要定时检测,有时需要外部事情激发这就出现了第2种解决方案,写一个内置类,可以放在事件监听的方法中,然后激发:2 5 参考3 1   SwingUtilities.invokeLater SwingUtilities.invokeLater(ne

Android02.常用布局及基本UI控件

一.Android学习API指南:[了解] 1. 应用的组成部分   App Components 1.1. 应用的基本原理    App Fundamentals 1.2. Activity      Activities 1.2.1. 片段    Fragments 1.2.2. 加载器     Loaders 1.2.3. 任务和返回堆    Tasks and Back Stack 1.3. Service服务   Services 1.3.1. 绑定服务     Bound Servi

C#学习之在辅助线程中修改UI控件----invoke方法

Invoke and BeginInvoke 转载地址:http://www.cnblogs.com/worldreason/archive/2008/06/09/1216127.html 在Invoke或者BeginInvoke的使用中无一例外地使用了委托Delegate,至于委托的本质请参考我的另一随笔:对.net事件的看法. 一.为什么Control类提供了Invoke和BeginInvoke机制? 关于这个问题的最主要的原因已经是dotnet程序员众所周知的,我在此费点笔墨再次记录到自己

C#子线程更新UI控件的方法总结

http://blog.csdn.net/jqncc/article/details/16342121 在winform C/S程序中经常会在子线程中更新控件的情况,桌面程序UI线程是主线程,当试图从子线程直接修改控件属性时会出现“从不是创建控件的线程访问它”的异常提示. 跨线程更新UI控件的常用方法有两种: 1.使用控件自身的invoke/BeginInvoke方法 2.使用SynchronizationContext的Post/Send方法更新 1.使用控件自身的invoke/BeginIn