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
            */
        if self.title == "UILabel"
        {
            var label = UILabel(frame: self.view.bounds)

  //这里也可以先创建再设置frame
            label.backgroundColor = UIColor.clearColor()
            label.textAlignment = NSTextAlignment.Center
            label.font = UIFont.systemFontOfSize(36)
            label.text = "Hello, Swift"
            self.view.addSubview(label)
        }
            /**
            *   2********************UIButton
            */
        else if self.title == "UIButton"
        {
            var button = UIButton.buttonWithType(UIButtonType.System) as? UIButton
            button!.frame = CGRectMake(110.0, 120.0, 100.0, 50.0)
            button!.backgroundColor = UIColor.grayColor()
            button?.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
            button!.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Highlighted)
            button?.setTitle("Touch Me", forState: UIControlState.Normal)
            button?.setTitle("Touch Me", forState: UIControlState.Highlighted)
            button?.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
            button!.tag = 100
            self.view.addSubview(button!)
        }
            /**
            *  3******************** UIImageView
            */
        else if self.title == "UIImageView"
        {
            var image     = UIImage(named: "swift-hero.png")
           
var 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)
        }
            /**
            *   4********************UISilder
            */
        else if self.title == "UISlider"
        {
            var slider = UISlider(frame:CGRectMake(60.0, 120.0, 200.0, 30.0))
            self.view.addSubview(slider)
        }
            /**
            *  5******************** UIWebView
            */
        else if self.title == "UIWebView"
        {
            var webView = UIWebView(frame:self.view.bounds)
            var url = NSURL(string: "http://caipiao.m.taobao.com")
            var request = NSURLRequest(URL: url!)
            webView.loadRequest(request)
            self.view.addSubview(webView)
        }
            /**
            *   6********************UISegmentedControl
            */
        else if self.title == "UISegmentedControl"
        {
            var segmentControl = UISegmentedControl(items:["A", "B", "C", "D"])
            segmentControl.frame = CGRectMake(110.0, 120.0, 100.0, 30.0)
            self.view.addSubview(segmentControl)
        }
            /**
            *   7********************UISwitch
            */
        else if self.title == "UISwitch"
        {
            var switchControl = UISwitch(frame:CGRectMake(130.0, 120.0, 100.0, 30.0))
            switchControl.on = true
            self.view.addSubview(switchControl)
        }
            /**
            *   8********************UItxetField
            */
        else if self.title == "UITextField"
        {
            var textField = UITextField(frame:CGRectMake(60.0, 120.0, 200.0, 30.0))
            textField.backgroundColor = UIColor.lightGrayColor()
            textField.placeholder = "input text"
            self.view.addSubview(textField)
        }
            /**
            *   9********************UIScrollView
            */
        else if self.title == "UIScrollView"
        {
            var scrollView = UIScrollView(frame:CGRectMake(60.0, 120.0, 200.0, 200.0))
            scrollView.pagingEnabled = true
            scrollView.showsVerticalScrollIndicator = false
            self.view.addSubview(scrollView)
            
            var fX: CGFloat = 0.0
            for(var i = 0; i < 3; ++i)
            {
                var view = UIView(frame:CGRectMake(fX, 0.0, 200.0, 200.0))
                fX += 200.0
                view.backgroundColor = UIColor.redColor()
                scrollView.addSubview(view)
            }
            scrollView.contentSize = CGSizeMake(3 * 200.0, 200.0)
            self.view.addSubview(scrollView)
        }
            /**
            *   10********************UISearchBar
            */
        else if self.title == "UISearchBar"
        {
            var 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)
        }
            /**
            *   11********************UIpageControl
            */
        else if self.title == "UIPageControl"
        {
            // PageControl
            var 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)
        }
            /**
            *   12********************UIDatePicker
            */
        else if self.title == "UIDatePicker"
        {
            var datePicker = UIDatePicker(frame:CGRectMake(0.0, 120.0, 200.0, 200.0))
            self.view.addSubview(datePicker)
        }
            /**
            *  13******************** UIPickerView
            */
        else if self.title == "UIPickerView"
        {
            var pickerView = UIPickerView(frame:CGRectMake(10.0, 120.0, 300.0, 200.0))
            pickerView.delegate = self
            pickerView.dataSource = self
            self.view.addSubview(pickerView)
        }
            /**
            *   14********************UIProgressView
            */
        else if self.title == "UIProgressView"
        {
            var 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)
        }
            /**
            *  15******************** UITextView
            */
        else if self.title == "UITextView"
        {
            var 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)
        }
            /**
            *   16********************UIToolbar
            */
        else if self.title == "UIToolbar"
        {
            var toolBar = UIToolbar(frame:CGRectMake(60.0, 120.0, 200.0, 30.0))

var flexibleSpace = UIBarButtonItem(barButtonSystemItem:UIBarButtonSystemItem.FlexibleSpace, target:nil, action:nil)
            var barBtnItemA = UIBarButtonItem(title: "A", style:UIBarButtonItemStyle.Plain, target:nil, action:nil)
            var barBtnItemB = UIBarButtonItem(title: "B", style:UIBarButtonItemStyle.Plain, target:nil, action:nil)
            var barBtnItemC = UIBarButtonItem(title: "C", style:UIBarButtonItemStyle.Plain, target:nil, action:nil)
            var 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)
        }
            /**
            *  16******************** UIActionSheet
            */
        else if self.title == "UIActionSheet"
        {
            // Button
            var button = UIButton.buttonWithType(UIButtonType.System) as? UIButton
            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("Show ActionSheet", forState: UIControlState.Normal)
            button?.setTitle("Show ActionSheet", forState: UIControlState.Highlighted)
            button?.addTarget(self, action: "showActionSheet", forControlEvents: UIControlEvents.TouchUpInside)
            button!.tag = 101
            self.view.addSubview(button!)
        }
            /**
            *   17********************UIActivityIndicatorView
            */
        else if self.title == "UIActivityIndicatorView"
        {
            var activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle:UIActivityIndicatorViewStyle.Gray)
            activityIndicatorView.frame = CGRectMake(140.0, 120.0, 40.0, 40.0)
            activityIndicatorView.startAnimating()
            self.view.addSubview(activityIndicatorView)
        }
        else
        {}
    }

下面是一些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开发!

时间: 2024-10-09 23:17:30

Swift学习之常用UI的使用的相关文章

学习IOS开发UI篇--UI知识点总结(四) UITabelView/UITableViewCell

UITabelView:常用属性 @property (nonatomic)          CGFloat    rowHeight;             // will return the default value if unset @property (nonatomic)          CGFloat     sectionHeaderHeight;   // will return the default value if unset @property (nonatom

学习IOS开发UI篇--UI知识点总结(三) UIScrollView/UIPageControl/NSTimer

UIScrollView:常用属性 @property(nonatomic)   UIEdgeInsets     contentInset;               // default UIEdgeInsetsZero. add additional scroll area around content @property(nonatomic,getter=isPagingEnabled) BOOL   pagingEnabled;     // default NO. if YES,

IOS开发-OC学习-常用功能代码片段整理

IOS开发-OC学习-常用功能代码片段整理 IOS开发中会频繁用到一些代码段,用来实现一些固定的功能.比如在文本框中输入完后要让键盘收回,这个需要用一个简单的让文本框失去第一响应者的身份来完成.或者是在做与URL有关的功能时,需要在Info.plist中添加一段代码进而实现让网址完成从Http到Https的转换,以及其他的一些功能. 在从一个新手到逐渐学会各种功能.代码.控件.方法如何使用的过程中,也在逐渐积累一些知识,但是一次总不会把这些东西都深刻记住并完全理解.所以在这儿记录下这些东西,用来

汇集了很多swift 学习指南

https://github.com/ipader/SwiftGuide 1,059   Unstar7,294 Fork1,966 ipader/SwiftGuide CodeIssues 0Pull requests 0WikiPulseGraphs 这份指南汇集了Swift语言主流学习资源,并以开发者的视角整理编排.http://dev.swiftguide.cn 376 commits 3 branches 0 releases 12 contributors Swift 100.0%

SpringMVC轻松学习-其他常用(四)

Spring MVC 3.0 深入 核心原理 1.      用户发送请求给服务器.url:user.do 2.      服务器收到请求.发现DispatchServlet可以处理.于是调用DispatchServlet. 3.      DispatchServlet内部,通过HandleMapping检查这个url有没有对应的Controller.如果有,则调用Controller. 4.      Controller开始执行. 5.      Controller执行完毕后,如果返回字

Swift学习——Swift基础详解(四)

A:小儿编程很不好! B:多半是不爱学,从看英文版开始,让你爱上编程! Type Aliases    类型重定义(typedef) Swift中重定义类型的关键字是typealias,至于怎么用,应该不必多说了,看例子: typealias AudioSample = UInt16 //定义了一个类型名称AudioSample,代表UInt16类型 var maxAmplitudeFound = AudioSample.min // maxAmplitudeFound is now 0 Boo

iOS ---Swift学习与复习

swift中文网 http://www.swiftv.cn http://swifter.tips/ http://objccn.io/ http://www.swiftmi.com/code4swift http://stackoverflow.com http://weibo.com/oldcoder 43个优秀的Swift开源项目推荐 https://developer.apple.com/swift/blog/ http://code.cocoachina.com http://swif

学习IOS开发UI篇--数据存储

iOS应用数据存储的常用方式 1.lXML属性列表(plist)归档 2.lPreference(偏好设置) 3.lNSKeyedArchiver归档(NSCoding) 4.lSQLite3 5.lCore Data Documents:保存应用运行时生成的需要持久化的数据,iTunes同步设备时会备份该目录.例如,游戏应用可将游戏存档保存在该目录 tmp:保存应用运行时所需的临时数据,使用完毕后再将相应的文件从该目录删除.应用没有运行时,系统也可能会清除该目录下的文件.iTunes同步设备时

学习IOS开发UI篇--UIScrollView/delegate/pagecontrol/UITimer

1.UIscrollView的属性 ================================================== 1.1 常见属性 @property(nonatomic) CGPoint contentOffset; 这个属性用来表示UIScrollView滚动的位置 @property(nonatomic) CGSize contentSize; 这个属性用来表示UIScrollView内容的尺寸,滚动范围(能滚多远) @property(nonatomic) UIE