概述
用了好些時間了解了一下Swift的語法,有人說Swift很簡單,其實在我看來,Swift有其簡單之處,也有其復雜之處,但我們應該注重的是學習Swift的語言之美!接下來開始進入UI的學習階段。
iOS開發(fā)過程中系統提供了很多UI相關的類,由于并不是完全了解,就慢慢摸索吧,我就是想著按照學習OC的方式來一步步開展我的Swift學習之路!
感謝:
http://www.lxweimin.com/p/d789d46c43fc
http://www.lxweimin.com/p/0f120d3c88b1# http://www.lxweimin.com/p/c7ed6ffb4694
的分享。
Swift Programming Language
Swift畢竟跟OC都是用來開發(fā)iOS應用的,所以UI控件都是一樣的。
UI控件
一切還是從打開Xcode開始:
創(chuàng)建一個工程
跟創(chuàng)建一個OC工程一樣,只不過Labguage改成Swift就可以了。
AppDelegate.swift文
//import 是導入文件/庫的關鍵字,相當于c語言中的include
//UIKit是iOS中所有的控件所在的庫文件
import UIKit
//UIApplicationMain:
//1.創(chuàng)建了一個UIApplication對象,代表當前應用程序,主要作用是用來檢測當前應用程序狀態(tài)的改變
//2.創(chuàng)建了一個遵守UIApplicationDelegate的協議的子類對象作為UIApplication的代理,作用是處理應用程序狀態(tài)的改變(創(chuàng)建AppDelegate的對象并且設置為UIApplication對象的代理)
@UIApplicationMain //調用了OC中的UIApplicationMain函數;它是ios應用程序的入口
//創(chuàng)建AppDelegate的對象并且設置為UIApplication對象的代理
class AppDelegate: UIResponder, UIApplicationDelegate {
//UIWindow:UIView
//window:窗口,一個應用想要展示在屏幕上,至少要有一個window.一個手機應用程序一般只有一個window
//應用程序中的所有的界面全部是展示在window上的
var window: UIWindow?
//當應用程序啟動成功后會自動調用這個方法
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
//在這個方法中來:
// 1.搭建應用程序中所有的界面
// 2.獲取應用程序需要展示的數據
// 3.使用界面展示數據
//注意:如果不在這個方法中去創(chuàng)建window,那么程序會通過Main.storyboard去創(chuàng)建應用程序界面
print("啟動應用程序")
return true
}
//當應用程序將要成為非活躍狀態(tài)的時候會自動調用這個方法。
// 活動狀態(tài):程序在屏幕上可見
// 非活躍狀態(tài):程序沒有顯示在屏幕上(常見三種情況:1.按home鍵進入后臺 2.來電打斷 3.在當前應用程序中打開其他應用程序)
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.
//在這個方法中一般是用來保存數據,比如暫停播放,保存播放時間位置,暫停游戲等等
print("程序將要成為非活躍狀態(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.
//在這個方法中一般是用來保存數據,比如暫停播放,保存播放時間位置,暫停游戲等等(和applicationWillResignActive方法可以選一個實現就可以了)
print("應用程序進入后臺")
}
//應用程序將要進入前臺的時候會自動調用
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("應用程序將要進入前臺")
}
//應用程序已經變成活躍狀態(tài)的時候會自動調用(常見三種情況:1.程序啟動之后 2.程序從后臺重新進入前臺 3.來電打斷結束)
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("應用已經成為活躍狀態(tài)")
}
//應用程序將要終止的時候會自動調用
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
print("應用程序將要終止")
}
}
創(chuàng)建一個Window窗口
//UIWindow:UIView
//window:窗口,一個應用想要展示在屏幕上,至少要有一個window.一個手機應用程序一般只有一個window
//應用程序中的所有的界面全部是展示在window上的
var window: UIWindow?
//當應用程序啟動成功后會自動調用這個方法
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
//在這個方法中來:
// 1.搭建應用程序中所有的界面
// 2.獲取應用程序需要展示的數據
// 3.使用界面展示數據
//注意:如果不在這個方法中去創(chuàng)建window,那么程序會通過Main.storyboard去創(chuàng)建應用程序界面
print("啟動應用程序")
//需要注意的是:
1>Swift3.0之后獲取屏幕尺寸已修改為UIScreen.main.bounds,"UIScreen.mainScreen().bounds"不在使用
2>創(chuàng)建顏色已修改為UIColor.yellow,不在使用"UIColor.yellowColor()"
//1.創(chuàng)建UIWindow對象
self.window = UIWindow.init(frame: UIScreen.main.bounds)
//2.設置根視圖控制器
//這里也需要注意,跟控制器是UIViewController,而不是ViewController,
//不需要導入頭文件,直接可以調用,具體什么鬼,我也不知道;但是我導入頭文件import ViewController會報錯的。
self.window?.rootViewController = ViewController()
//3.設置背景顏色
self.window?.backgroundColor = UIColor.yellow
return true
}
這是一個Window
UIView
簡單常用的一些方法,掌握這些基本都是夠用的。Swift3.0之后方法變化很大,使用時多查看用法。其實只要是學過OC的小伙伴,上手還是很快的,方法基本還是那些方法,只不過是換了書寫方式,其余的自己動手多敲敲就都出來了。至于UIView的動畫以后再做研究吧。
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)
//旋轉
//參數:旋轉角度(圓周率對應的角度值)
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
//獲取一個視圖的父視圖
let superView = view.superview
superView?.backgroundColor = UIColor.black
//獲取一個視圖的所有的子視圖
let subViews = self.view.subviews
print(subViews)
self.view.addSubview(view)
效果圖:
這是創(chuàng)建的UIView
UILabel
//根據文字設置label的大小
let str = "qwertyuiop[asdfghjklweqwertyui歐普qwertyu iop[3ertyuiop rtyuiopsdfghjkrtyuio"
//計算顯示指定文字所需要的最小空間
//1.將swift的字符串轉換成OC的字符串
let ocStr = str as NSString
//2.計算字符串的大小
//參數1:限制顯示當前字符串的最大寬度和最大高度
//參數2:設置渲染方式(UsesLineFragmentOrigin)
//參數3:確定文字的字體(大小)
//NSFontAttributeName ->字體對應的key值
//NSForegroundColorAttributeName -> 文字顏色對應的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 = "這是一個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
//之前方法是這樣的,但是現在并沒有實現效果,不知道咋搞。
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)建一個圖片對象(注意:如果圖片的格式是png,那么圖片名的后綴可以省略。但是其他格式的圖片的圖片名的后綴不能省略)
//img.image = UIImage.init(named: "img")
//b.通過圖片路徑去創(chuàng)建一個圖片對象
//將文件(除了swift文件)放到工程中,實質是放到了當前應用程序的包文件中
//(想要拿到工程中的圖片路徑先要獲取包文件;)
//拿到包中的指定的文件的路徑
let imagePath = Bundle.main.path(forResource: "img", ofType: "png")
img.image = UIImage.init(contentsOfFile: imagePath!)
//c.比較通過圖片名和通過圖片地址創(chuàng)建圖片對象的兩種方法:
//(1).通過圖片名創(chuàng)建的圖片對象在程序結束后才會被銷毀,只會創(chuàng)建一次;通過圖片地址創(chuàng)建圖片對象是當前圖片對象不再使用的時候就銷毀
//(2)使用圖片名創(chuàng)建圖片的情況:創(chuàng)建小圖標的時候;在工程中會重復使用的圖片
//(3)使用圖片地址創(chuàng)建圖片對象的情況:不會頻繁的在多個界面出現的大圖
//內容模式
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("這是一個按鈕", 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之后對于按鈕的點擊事件的寫法變化很大。
// #selector(ViewController.addview(_:)這么寫真心感覺別扭,目前還沒有理解這么寫的美感,慢慢體會吧。
// ViewController:我理解的應該就是所在的控制器
// addView:我理解的應該就是按鈕的點擊方法名
// 注意: _ 如果這里寫的是這個下劃線,那么在func里面也是對應的_,如果換成隨便起的名字,那么func里面也要對應上。
btn.addTarget(self, action: #selector(ViewController.addview(_:)), for: .touchUpInside)
self.view.addSubview(btn)
// 按鈕點擊事件
func addview(_ sender:UIButton) {
print("點擊了按鈕")
}
這是創(chuàng)建的UIButton
UITextField
常用方法:
let textField = UITextField()
textField.frame = CGRect(x: 20, y: 300, width: 300, height: 44)
// textField.text = "這是一個輸入框"
textField.placeholder = "請輸入賬號"
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:
//參數:當前這個協議對應的委托方
//當文本輸入框已經開始編輯的時候會自動調用這個方法
func textFieldDidBeginEditing(_ textField: UITextField) {
print("已經開始編輯")
}
//當文本框將要結束的時候自動調用這個方法
//返回值:設置當前的TextField是否可以結束編輯(默認是true)
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
//例如要求文本框的文本長度大于等于11才能結束
if (textField.text?.characters.count)! >= 11{
return true
}
return false
}
//當文本框已經結束編輯(光標消失)的時候自動調用這個方法
func textFieldDidEndEditing(_ textField: UITextField) {
print("已經結束編輯")
}
//當TextField彈出來的鍵盤按鍵被點擊時會自動調用
//參數2:當前輸入字符所在的位置
//參數3:當前輸入的字符串(字符轉換成的字符串)
//返回值:是否可以改變TextField的text的值(默認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的值
}
//點擊回車按鈕
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
print("返回按鈕被點擊")
//收起鍵盤(結束編輯)
//1.放棄第一響應者
textField.resignFirstResponder()
//2.直接讓指定的textField結束編輯
textField.endEditing(true)
//3.讓self.view上的所有的子視圖都結束編輯
self.view.endEditing(true)
return true
}
//返回值:設置當前TextField是否可以進行編輯(默認為true)
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return true //可以編輯
// return false 不能處于編輯狀態(tài)(不能進行編輯),雞肋方法,基本不會用這個方法
}
//設置文本是否能被清除,默認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 = "這是一個textView"
// 屬性和TextField基本一致,不再累贅。
self.view.addSubview(textView)
這是創(chuàng)建的UITextView
UIAlertViewController
// 風格1:
let alert = UIAlertController(title: "這是一個彈框", message: "親、么么噠~", preferredStyle: .alert)
let sure = UIAlertAction(title: "確定", style: .destructive) { (alert:UIAlertAction) in
print("確定")
// 風格2:
//1.創(chuàng)建表單視圖
//參數1:標題,參數2:信息
//參數3:風格 .Alert - 警告框 .actionSheet - 表單視圖
let alterController = UIAlertController(title: "標題", message: "消息", preferredStyle: .actionSheet)
//2.添加到界面上
//參數1:需要顯示的試圖控制器,參數2:是否需要動畫, 參數3:顯示完成后需要做什么
self.present(alterController, animated: true, completion: nil)
//添加按鈕
//參數1:當前選項對應按鈕上的文字
//參數2:風格 .default - 連在一起 .cancel - 單獨分開顯示 .destructive - title顯示顏色是紅色
//參數3:當按鈕點擊后需要做什么
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)
這是一個彈框
UIDatePicker
創(chuàng)建一個UIDatePicker
let datePicker = UIDatePicker()
datePicker.center = CGPoint(x: 200, y: 620)
datePicker.tag = 1
self.view.addSubview(datePicker)
取到當前選中的日期
//這里沒有寫取消、確定按鈕,處于省事就這么寫了,原理是一樣的;
//如果好好寫一個picker的話,也是這樣的用法取到“dateAndTime”就是當前選中的日期
let datePicker = self.view.viewWithTag(1) as! UIDatePicker
//獲取日期拾取起的日期值
let date = datePicker.date
//新建一個日期格式化對象,用來實現日期的格式化
let dateFormater = DateFormatter()
//設置日期的格式,大寫的H表示采用24小時制
dateFormater.dateFormat = "yyyy-MM-dd HH:mm"
//將日期轉換為指定格式的字符串
let dateAndTime = dateFormater.string(from: date)
let alert = UIAlertController(title: "當前選中的時間", message: dateAndTime, preferredStyle: .alert)
let alertAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(alertAction)
self.present(alert, animated: true, completion: nil)
這是一個UIDatePicker
好了,常用的基本UI控件也就是這些,像那些什么
UISegmentedControl 、UIStepper、UISlider也不怎么用,我也沒看,需要用到的話再看吧,還是那句話,會OC的,掌握非常快,只是換個了寫法而已。
接下來,就要學習控制器之類的了,另開一篇文章。
如果您覺得我的文章幫到了你,記得給個Star啊_
如果有需要的代碼點擊這里:
https://github.com/Baiyongyu/Swift3.0-UI-UI-.git