Swift UIButton&UIAlertController — DAY16

工程師卡卡
6 min readJun 7, 2021

--

UIButton 按鈕除了可以使用文字之外,也可以設置成圖片。

UIAlertController 使用UIButton來呼叫跳窗事件。

UIButton也事先宣告一個常數,後面的type是樣式,像是.contactAdd就是一個螢幕左上方的+號按鈕。

let myButton1 = UIButton(type: .contactAdd)myButton1.center = CGPoint(x: 50, y: 50)self.view.addSubview(myButton1)
// 使用 UIButton(frame:) 建立一個 UIButtonlet myButton = UIButton(frame: CGRect(x: 100, y: 500, width: 50, height: 30))
// 按鈕文字myButton.setTitle("按我", for: .normal)// 按鈕文字顏色myButton.setTitleColor(UIColor.white,for: .normal)// 按鈕是否可以使用myButton.isEnabled = true// 按鈕背景顏色myButton.backgroundColor = UIColor.darkGray//TargetmyButton.addTarget(self, action: #selector(clickButton), for: .touchUpInside)self.view.addSubview(myButton)//建立一個func 給target使用
@objc func clickButton(){if self.view.backgroundColor!.isEqual(UIColor.white){self.view.backgroundColor=UIColor.black}else{self.view.backgroundColor=UIColor.white}}

主要比較特別的是 addTarget(target, action:, for:):

  • target:當事件發生時,要呼叫哪一個物件。(self)
  • action:呼叫的物件要執行的方法,以#selector()來指定,ViewController.clickButton指的就是ViewController類別的clickButton方法。(clickButton)
  • for:觸發的事件。(.touchUpInside)

設置使用圖片的按鈕

// 建立一個播放按鈕
let playButton = UIButton(
frame: CGRect(x: 0, y: 0, width: 64, height: 64))
// 設置播放按鈕的圖片
playButton.setImage(
UIImage(named: "play"), forState: .Normal)
// 設置按下播放按鈕的動作的方法
playButton.addTarget(
self,
action: #selector(ViewController.play),
forControlEvents: .TouchUpInside)
// 設置位置及放入畫面中
playButton.center = CGPoint(
x: fullScreenSize.width * 0.35,
y: fullScreenSize.height * 0.65)
self.view.addSubview(playButton)
// 建立一個停止按鈕
let stopButton = UIButton(
frame: CGRect(x: 0, y: 0, width: 64, height: 64))
// 設置停止按鈕的圖片
stopButton.setImage(
UIImage(named: "stop"), forState: .Normal)
// 設置按下停止按鈕的動作的方法
stopButton.addTarget(
self,
action: #selector(ViewController.stop),
forControlEvents: .TouchUpInside)
// 設置位置及放入畫面中
stopButton.center = CGPoint(
x: fullScreenSize.width * 0.65,
y: fullScreenSize.height * 0.65)
self.view.addSubview(stopButton)

UIAlertController

現建立一個按鈕,在使用addTarget來呼叫simpleHint func

UIAlertController(title:,message:,preferredStyle:)建立一個提示窗:

preferredStyle:提示框的類型,這邊填寫 .Alert ,會顯示在畫面中間,另外如果填寫 .ActionSheet 則是顯示在畫面底部。

UIAlertAction(title:,style:,style:{})建立跳窗動作:

  • title:按鈕的文字。
  • style:按鈕的樣式,可選擇.Cancel.Default.Destructive等等。
  • handler:按下按鈕後要執行的動作,是一個型別為(action: UIAlertAction!) -> Void閉包,如果不要有動作則是填入nil
@objc func simpleHint(){// 建立一個提示框let alertController = UIAlertController(title: "提示",message: "一個簡單提示,請按確認繼續",preferredStyle: .alert)// 建立[確認]按鈕let okAction = UIAlertAction(title: "確認",style: .default,handler: {(action: UIAlertAction!) -> Void inprint("按下確認後,閉包裡的動作")})alertController.addAction(okAction)// 顯示提示框self.present(alertController,animated: true,completion: nil)}

按鈕設置好之後,再使用alertController.addAction()方法,將按鈕加入到提示框控制器中。

最後則是對self使用present()方法來顯示提示框。

--

--

工程師卡卡
工程師卡卡

Written by 工程師卡卡

Frontend developer Swift baby level

No responses yet