Swift3.0-學(xué)習(xí)之路之基礎(chǔ)UI篇

概述

用了好些時(shí)間了解了一下Swift的語法,有人說Swift很簡單,其實(shí)在我看來,Swift有其簡單之處,也有其復(fù)雜之處,但我們應(yīng)該注重的是學(xué)習(xí)Swift的語言之美!接下來開始進(jìn)入U(xiǎn)I的學(xué)習(xí)階段。
iOS開發(fā)過程中系統(tǒng)提供了很多UI相關(guān)的類,由于并不是完全了解,就慢慢摸索吧,我就是想著按照學(xué)習(xí)OC的方式來一步步開展我的Swift學(xué)習(xí)之路!
感謝:
http://www.itdecent.cn/p/d789d46c43fc
http://www.itdecent.cn/p/0f120d3c88b1# http://www.itdecent.cn/p/c7ed6ffb4694
的分享。

Swift Programming Language

Swift畢竟跟OC都是用來開發(fā)iOS應(yīng)用的,所以UI控件都是一樣的。

UI控件

一切還是從打開Xcode開始:

創(chuàng)建一個(gè)工程

跟創(chuàng)建一個(gè)OC工程一樣,只不過Labguage改成Swift就可以了。

AppDelegate.swift文

//import 是導(dǎo)入文件/庫的關(guān)鍵字,相當(dāng)于c語言中的include
//UIKit是iOS中所有的控件所在的庫文件
import UIKit
//UIApplicationMain:
//1.創(chuàng)建了一個(gè)UIApplication對(duì)象,代表當(dāng)前應(yīng)用程序,主要作用是用來檢測當(dāng)前應(yīng)用程序狀態(tài)的改變
//2.創(chuàng)建了一個(gè)遵守UIApplicationDelegate的協(xié)議的子類對(duì)象作為UIApplication的代理,作用是處理應(yīng)用程序狀態(tài)的改變(創(chuàng)建AppDelegate的對(duì)象并且設(shè)置為UIApplication對(duì)象的代理)

@UIApplicationMain //調(diào)用了OC中的UIApplicationMain函數(shù);它是ios應(yīng)用程序的入口

//創(chuàng)建AppDelegate的對(duì)象并且設(shè)置為UIApplication對(duì)象的代理
class AppDelegate: UIResponder, UIApplicationDelegate {
    //UIWindow:UIView
    //window:窗口,一個(gè)應(yīng)用想要展示在屏幕上,至少要有一個(gè)window.一個(gè)手機(jī)應(yīng)用程序一般只有一個(gè)window
    //應(yīng)用程序中的所有的界面全部是展示在window上的
    var window: UIWindow?

    //當(dāng)應(yīng)用程序啟動(dòng)成功后會(huì)自動(dòng)調(diào)用這個(gè)方法
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        //在這個(gè)方法中來:
        //        1.搭建應(yīng)用程序中所有的界面
        //        2.獲取應(yīng)用程序需要展示的數(shù)據(jù)
        //        3.使用界面展示數(shù)據(jù)
        //注意:如果不在這個(gè)方法中去創(chuàng)建window,那么程序會(huì)通過Main.storyboard去創(chuàng)建應(yīng)用程序界面
        print("啟動(dòng)應(yīng)用程序")
        return true
    }

    //當(dāng)應(yīng)用程序?qū)⒁蔀榉腔钴S狀態(tài)的時(shí)候會(huì)自動(dòng)調(diào)用這個(gè)方法。
    //    活動(dòng)狀態(tài):程序在屏幕上可見
    //    非活躍狀態(tài):程序沒有顯示在屏幕上(常見三種情況:1.按home鍵進(jìn)入后臺(tái) 2.來電打斷  3.在當(dāng)前應(yīng)用程序中打開其他應(yīng)用程序)
    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
        
        //在這個(gè)方法中一般是用來保存數(shù)據(jù),比如暫停播放,保存播放時(shí)間位置,暫停游戲等等
        print("程序?qū)⒁蔀榉腔钴S狀態(tài)")
    }

    //當(dāng)應(yīng)用程序已經(jīng)進(jìn)入后臺(tái)的時(shí)候會(huì)自動(dòng)調(diào)用(進(jìn)入后臺(tái)只有按home鍵)
    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
        
        //在這個(gè)方法中一般是用來保存數(shù)據(jù),比如暫停播放,保存播放時(shí)間位置,暫停游戲等等(和applicationWillResignActive方法可以選一個(gè)實(shí)現(xiàn)就可以了)
        print("應(yīng)用程序進(jìn)入后臺(tái)")
    }

    //應(yīng)用程序?qū)⒁M(jìn)入前臺(tái)的時(shí)候會(huì)自動(dòng)調(diào)用
    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.      
        print("應(yīng)用程序?qū)⒁M(jìn)入前臺(tái)")
    }

    //應(yīng)用程序已經(jīng)變成活躍狀態(tài)的時(shí)候會(huì)自動(dòng)調(diào)用(常見三種情況:1.程序啟動(dòng)之后  2.程序從后臺(tái)重新進(jìn)入前臺(tái)   3.來電打斷結(jié)束)
    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.       
        print("應(yīng)用已經(jīng)成為活躍狀態(tài)")
    }

    //應(yīng)用程序?qū)⒁K止的時(shí)候會(huì)自動(dòng)調(diào)用
    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.      
        print("應(yīng)用程序?qū)⒁K止")
    }
}

創(chuàng)建一個(gè)Window窗口

//UIWindow:UIView
    //window:窗口,一個(gè)應(yīng)用想要展示在屏幕上,至少要有一個(gè)window.一個(gè)手機(jī)應(yīng)用程序一般只有一個(gè)window
    //應(yīng)用程序中的所有的界面全部是展示在window上的
    var window: UIWindow?

    //當(dāng)應(yīng)用程序啟動(dòng)成功后會(huì)自動(dòng)調(diào)用這個(gè)方法
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        //在這個(gè)方法中來:
        //        1.搭建應(yīng)用程序中所有的界面
        //        2.獲取應(yīng)用程序需要展示的數(shù)據(jù)
        //        3.使用界面展示數(shù)據(jù)
        //注意:如果不在這個(gè)方法中去創(chuàng)建window,那么程序會(huì)通過Main.storyboard去創(chuàng)建應(yīng)用程序界面
        print("啟動(dòng)應(yīng)用程序")
        
        //需要注意的是:
         1>Swift3.0之后獲取屏幕尺寸已修改為UIScreen.main.bounds,"UIScreen.mainScreen().bounds"不在使用
         2>創(chuàng)建顏色已修改為UIColor.yellow,不在使用"UIColor.yellowColor()"

        //1.創(chuàng)建UIWindow對(duì)象
        self.window = UIWindow.init(frame: UIScreen.main.bounds)
        //2.設(shè)置根視圖控制器
        //這里也需要注意,跟控制器是UIViewController,而不是ViewController,
        //不需要導(dǎo)入頭文件,直接可以調(diào)用,具體什么鬼,我也不知道;但是我導(dǎo)入頭文件import ViewController會(huì)報(bào)錯(cuò)的。
        self.window?.rootViewController = ViewController()
        //3.設(shè)置背景顏色
        self.window?.backgroundColor = UIColor.yellow
        
        return true
    }
這是一個(gè)Window

UIView

簡單常用的一些方法,掌握這些基本都是夠用的。Swift3.0之后方法變化很大,使用時(shí)多查看用法。其實(shí)只要是學(xué)過OC的小伙伴,上手還是很快的,方法基本還是那些方法,只不過是換了書寫方式,其余的自己動(dòng)手多敲敲就都出來了。至于UIView的動(dòng)畫以后再做研究吧。

        let view = UIView()
        view.frame = CGRect(x: 50, y: 50, width: 100, height: 50)
        view.center = CGPoint(x: 200, y: 200)
//        view.backgroundColor = UIColor.green
        view.backgroundColor = UIColor.init(white: 0.5, alpha: 1)
        
        //transform(形變)
        //縮放
        view.transform = CGAffineTransform(scaleX: 0.8, y: 2.5)
        //旋轉(zhuǎn)
        //參數(shù):旋轉(zhuǎn)角度(圓周率對(duì)應(yīng)的角度值)
        view.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi/4 / 2))
        
        view.tag = 10
        
        view.layer.masksToBounds = true
        view.layer.cornerRadius = 20
        view.layer.borderColor = UIColor.red.cgColor
        view.layer.borderWidth = 5
        
        //獲取一個(gè)視圖的父視圖
        let superView = view.superview
        superView?.backgroundColor = UIColor.black
        
        //獲取一個(gè)視圖的所有的子視圖
        let subViews = self.view.subviews
        print(subViews)
        
        
        self.view.addSubview(view)

效果圖:

這是創(chuàng)建的UIView

UILabel

        //根據(jù)文字設(shè)置label的大小
        let str = "qwertyuiop[asdfghjklweqwertyui歐普qwertyu iop[3ertyuiop rtyuiopsdfghjkrtyuio"
        //計(jì)算顯示指定文字所需要的最小空間
        //1.將swift的字符串轉(zhuǎn)換成OC的字符串
        let ocStr = str as NSString
        //2.計(jì)算字符串的大小
        //參數(shù)1:限制顯示當(dāng)前字符串的最大寬度和最大高度
        //參數(shù)2:設(shè)置渲染方式(UsesLineFragmentOrigin)
        //參數(shù)3:確定文字的字體(大小)
        //NSFontAttributeName ->字體對(duì)應(yīng)的key值
        //NSForegroundColorAttributeName -> 文字顏色對(duì)應(yīng)的key值
        
        let strSize = ocStr.boundingRect(with: CGSize(width: 300, height: 1000000000), options: NSStringDrawingOptions(rawValue: 1), attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 17)], context: nil).size
        print(strSize)
        
        
        let lb = UILabel()
        lb.frame = CGRect(x: 20, y: 80, width: 100, height: 30)
//        lb.text = "這是一個(gè)label"
        lb.numberOfLines = 0
        lb.textColor = UIColor.red
        lb.backgroundColor = UIColor.white
        lb.font = UIFont.systemFont(ofSize: 15)
        lb.shadowColor = UIColor.black
        lb.textAlignment = .center
        lb.shadowOffset = CGSize(width: -1, height: 1)
        
        
        lb.text = str
        //之前方法是這樣的,但是現(xiàn)在并沒有實(shí)現(xiàn)效果,不知道咋搞。
        
        self.view.addSubview(lb)

效果圖:

這是創(chuàng)建的UILabel

UIImageView

        let img = UIImageView()
        img.frame = CGRect(x: 70, y: 150, width: 60, height: 60)
        //a.通過圖片名去創(chuàng)建一個(gè)圖片對(duì)象(注意:如果圖片的格式是png,那么圖片名的后綴可以省略。但是其他格式的圖片的圖片名的后綴不能省略)
        //img.image = UIImage.init(named: "img")
        
        //b.通過圖片路徑去創(chuàng)建一個(gè)圖片對(duì)象
        //將文件(除了swift文件)放到工程中,實(shí)質(zhì)是放到了當(dāng)前應(yīng)用程序的包文件中
        //(想要拿到工程中的圖片路徑先要獲取包文件;)
        
        //拿到包中的指定的文件的路徑
        let imagePath = Bundle.main.path(forResource: "img", ofType: "png")
        img.image = UIImage.init(contentsOfFile: imagePath!)
        
        //c.比較通過圖片名和通過圖片地址創(chuàng)建圖片對(duì)象的兩種方法:
        //(1).通過圖片名創(chuàng)建的圖片對(duì)象在程序結(jié)束后才會(huì)被銷毀,只會(huì)創(chuàng)建一次;通過圖片地址創(chuàng)建圖片對(duì)象是當(dāng)前圖片對(duì)象不再使用的時(shí)候就銷毀
        //(2)使用圖片名創(chuàng)建圖片的情況:創(chuàng)建小圖標(biāo)的時(shí)候;在工程中會(huì)重復(fù)使用的圖片
        //(3)使用圖片地址創(chuàng)建圖片對(duì)象的情況:不會(huì)頻繁的在多個(gè)界面出現(xiàn)的大圖
        
        //內(nèi)容模式
        img.contentMode = .scaleToFill
        
        self.view.addSubview(img)
這是創(chuàng)建的UIImageView

UIButton

        let btn = UIButton()
        btn.frame = CGRect(x: 100, y: 250, width: 200, height: 40)
        btn.setTitle("這是一個(gè)按鈕", for: .normal)
        btn.setTitleColor(UIColor.red, for: .normal)
        btn.backgroundColor = UIColor.white
//        btn.setImage(UIImage.init(named: "img"), for: .normal)
//        btn.setBackgroundImage(UIImage.init(named: "img"), for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        btn.titleLabel?.textAlignment = .center
        //需要注意的是:Swift3.0之后對(duì)于按鈕的點(diǎn)擊事件的寫法變化很大。
        // #selector(ViewController.addview(_:)這么寫真心感覺別扭,目前還沒有理解這么寫的美感,慢慢體會(huì)吧。
        // ViewController:我理解的應(yīng)該就是所在的控制器
        // addView:我理解的應(yīng)該就是按鈕的點(diǎn)擊方法名
        // 注意: _ 如果這里寫的是這個(gè)下劃線,那么在func里面也是對(duì)應(yīng)的_,如果換成隨便起的名字,那么func里面也要對(duì)應(yīng)上。
        btn.addTarget(self, action: #selector(ViewController.addview(_:)), for: .touchUpInside)
        
        self.view.addSubview(btn)
// 按鈕點(diǎn)擊事件
   func addview(_ sender:UIButton) {
       print("點(diǎn)擊了按鈕")
   }
這是創(chuàng)建的UIButton

UITextField

常用方法:

        let textField = UITextField()
        textField.frame = CGRect(x: 20, y: 300, width: 300, height: 44)
//        textField.text = "這是一個(gè)輸入框"
        textField.placeholder = "請(qǐng)輸入賬號(hào)"
        textField.isSecureTextEntry = true
        textField.borderStyle = .roundedRect
        textField.clearButtonMode = .whileEditing
        textField.keyboardType = .numberPad
        textField.delegate = self
        textField.returnKeyType = .go
        
        let leftImg = UIImageView()
        leftImg.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        leftImg.image = UIImage.init(named: "img")
        textField.leftView = leftImg
        textField.leftViewMode = .always
            
        self.view.addSubview(textField)

代理UITextFieldDelegate:

    //參數(shù):當(dāng)前這個(gè)協(xié)議對(duì)應(yīng)的委托方
    //當(dāng)文本輸入框已經(jīng)開始編輯的時(shí)候會(huì)自動(dòng)調(diào)用這個(gè)方法
    func textFieldDidBeginEditing(_ textField: UITextField) {
        print("已經(jīng)開始編輯")
    }
    
    //當(dāng)文本框?qū)⒁Y(jié)束的時(shí)候自動(dòng)調(diào)用這個(gè)方法
    //返回值:設(shè)置當(dāng)前的TextField是否可以結(jié)束編輯(默認(rèn)是true)
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        //例如要求文本框的文本長度大于等于11才能結(jié)束
        if (textField.text?.characters.count)! >= 11{
            return true
        }
        return false
    }
    
    //當(dāng)文本框已經(jīng)結(jié)束編輯(光標(biāo)消失)的時(shí)候自動(dòng)調(diào)用這個(gè)方法
    func textFieldDidEndEditing(_ textField: UITextField) {
        print("已經(jīng)結(jié)束編輯")
    }
    
    //當(dāng)TextField彈出來的鍵盤按鍵被點(diǎn)擊時(shí)會(huì)自動(dòng)調(diào)用
    //參數(shù)2:當(dāng)前輸入字符所在的位置
    //參數(shù)3:當(dāng)前輸入的字符串(字符轉(zhuǎn)換成的字符串)
    //返回值:是否可以改變TextField的text的值(默認(rèn)true)
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        //        print(range)
        //        print(string)
        if string == "0"{
            print("sb")
        }
        return true //可以改變TextField的text的值
        //return false 不可以改變TextField的text的值
    }
    
    //點(diǎn)擊回車按鈕
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        print("返回按鈕被點(diǎn)擊")
        //收起鍵盤(結(jié)束編輯)
        //1.放棄第一響應(yīng)者
        textField.resignFirstResponder()
        //2.直接讓指定的textField結(jié)束編輯
        textField.endEditing(true)
        //3.讓self.view上的所有的子視圖都結(jié)束編輯
        self.view.endEditing(true)
        return true
    }
    
    //返回值:設(shè)置當(dāng)前TextField是否可以進(jìn)行編輯(默認(rèn)為true)
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        return true //可以編輯
        // return false 不能處于編輯狀態(tài)(不能進(jìn)行編輯),雞肋方法,基本不會(huì)用這個(gè)方法
    }
    
    //設(shè)置文本是否能被清除,默認(rèn)true,雞肋方法,一般不用
    func textFieldShouldClear(_ textField: UITextField) -> Bool {
        return true
    }
這是創(chuàng)建的UITextField

UITextView

        let textView = UITextView()
        textView.frame = CGRect(x: 50, y: 350, width: 300, height: 100)
        textView.text = "這是一個(gè)textView"
//        屬性和TextField基本一致,不再累贅。
        self.view.addSubview(textView)
這是創(chuàng)建的UITextView

UIAlertViewController

        // 風(fēng)格1:
        let alert = UIAlertController(title: "這是一個(gè)彈框", message: "親、么么噠~", preferredStyle: .alert)
        let sure = UIAlertAction(title: "確定", style: .destructive) { (alert:UIAlertAction) in
            print("確定")
            // 風(fēng)格2:
            //1.創(chuàng)建表單視圖
            //參數(shù)1:標(biāo)題,參數(shù)2:信息
            //參數(shù)3:風(fēng)格 .Alert - 警告框  .actionSheet - 表單視圖
            let alterController = UIAlertController(title: "標(biāo)題", message: "消息", preferredStyle: .actionSheet)
            
            //2.添加到界面上
            //參數(shù)1:需要顯示的試圖控制器,參數(shù)2:是否需要?jiǎng)赢嫞?參數(shù)3:顯示完成后需要做什么
            self.present(alterController, animated: true, completion: nil)
            //添加按鈕
            //參數(shù)1:當(dāng)前選項(xiàng)對(duì)應(yīng)按鈕上的文字
            //參數(shù)2:風(fēng)格 .default - 連在一起  .cancel - 單獨(dú)分開顯示  .destructive - title顯示顏色是紅色
            //參數(shù)3:當(dāng)按鈕點(diǎn)擊后需要做什么
            let action = UIAlertAction(title: "按鈕", style: .destructive, handler: nil)
            alterController.addAction(action)
        }
        
        let cancle = UIAlertAction(title: "取消", style: .cancel) { (alert:UIAlertAction) in
              print("取消")
        }

        alert.addAction(sure)
        alert.addAction(cancle)
        self.present(alert, animated: true, completion: nil)
這是一個(gè)彈框

UIDatePicker

創(chuàng)建一個(gè)UIDatePicker

        let datePicker = UIDatePicker()
        datePicker.center = CGPoint(x: 200, y: 620)
        datePicker.tag = 1
        self.view.addSubview(datePicker)

取到當(dāng)前選中的日期

        //這里沒有寫取消、確定按鈕,處于省事就這么寫了,原理是一樣的;
        //如果好好寫一個(gè)picker的話,也是這樣的用法取到“dateAndTime”就是當(dāng)前選中的日期
        
        let datePicker = self.view.viewWithTag(1) as! UIDatePicker
        //獲取日期拾取起的日期值
        let date = datePicker.date
        //新建一個(gè)日期格式化對(duì)象,用來實(shí)現(xiàn)日期的格式化
        let dateFormater = DateFormatter()
        //設(shè)置日期的格式,大寫的H表示采用24小時(shí)制
        dateFormater.dateFormat = "yyyy-MM-dd HH:mm"
        //將日期轉(zhuǎn)換為指定格式的字符串
        let dateAndTime = dateFormater.string(from: date)
        
        let alert = UIAlertController(title: "當(dāng)前選中的時(shí)間", message: dateAndTime, preferredStyle: .alert)
        let alertAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        alert.addAction(alertAction)
        self.present(alert, animated: true, completion: nil)

這是一個(gè)UIDatePicker

好了,常用的基本UI控件也就是這些,像那些什么
UISegmentedControl 、UIStepper、UISlider也不怎么用,我也沒看,需要用到的話再看吧,還是那句話,會(huì)OC的,掌握非???,只是換個(gè)了寫法而已。
接下來,就要學(xué)習(xí)控制器之類的了,另開一篇文章。
如果您覺得我的文章幫到了你,記得給個(gè)Star啊_
如果有需要的代碼點(diǎn)擊這里:
https://github.com/Baiyongyu/Swift3.0-UI-UI-.git

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 轉(zhuǎn)載自:https://github.com/Tim9Liu9/TimLiu-iOS[https://github...
    香橙柚子閱讀 9,172評(píng)論 0 36
  • A:“我覺得巫婆以后的男朋友肯定會(huì)是個(gè)大叔” B:“你怎么能這樣侮辱她?” A:“不是啊,大叔也有帥的啊” 巫婆:...
    簡書是啥閱讀 452評(píng)論 0 1
  • 一天讀完了《血色浪漫》這本書 書中的主人公無疑是鐘躍民 我以前有印象,《血色浪漫》拍成了電視劇,好像劉燁是主角,我...
    雪域紅妝閱讀 780評(píng)論 0 2
  • 處理移動(dòng)端 click 事件 300 毫秒延遲, 由 FT Labs 開發(fā),Github 項(xiàng)目地址:https:/...
    與蟒唯舞閱讀 1,453評(píng)論 0 1
  • 遍歷可變數(shù)組的同時(shí)刪除數(shù)組元素 NSMutableArray *copyArray = [NSMutableArr...
    seventhboy閱讀 327評(píng)論 0 1

友情鏈接更多精彩內(nèi)容