目錄:[Swift]Xcode實際操做html
本文將演示圖片按鈕的使用swift
在項目導航區,打開視圖控制器的代碼文件【ViewController.swift】ide
1 import UIKit 2 3 class ViewController: UIViewController { 4 5 override func viewDidLoad() { 6 super.viewDidLoad() 7 // Do any additional setup after loading the view, typically from a nib. 8 //首先建立一個普通的圓角按鈕 9 let bt1 = UIButton(type: UIButton.ButtonType.roundedRect) 10 //建立一個位置在(31,100),尺寸爲(257,60)的顯示區域 11 let rect = CGRect(x: 31, y: 100, width: 257, height: 60) 12 //設置按鈕對象的顯示區域 13 bt1.frame = rect 14 15 //從項目資源文件夾中,讀取一張圖片素材 16 let image = UIImage(named: "Button") 17 //將圖片設定爲,按鈕在正常狀態下的背景圖片, 18 //也能夠給按鈕的按下狀態,失效狀態,指定各自的背景圖片。 19 bt1.setBackgroundImage(image, for: .normal) 20 //設置按鈕在正常狀態下的標題文字 21 bt1.setTitle("Tap Me", for: .normal) 22 //設置按鈕在正常狀態下,標題的顏色爲白色 23 bt1.setTitleColor(UIColor.white, for: .normal) 24 //設置按鈕文字的字體形狀了字體大小 25 bt1.titleLabel?.font = UIFont(name: "Arial", size: 24) 26 //給按鈕添加點擊事件 27 bt1.addTarget(self, action: #selector(ViewController.buttonTap(_:)), for: UIControl.Event.touchUpInside) 28 29 //將圖片按鈕添加到當前視圖控制器的根視圖 30 self.view.addSubview(bt1) 31 } 32 33 //添加一個方法,執行按鈕的點擊事件 34 @objc func buttonTap(_ button:UIButton) 35 { 36 //建立一個警告彈出窗口,當按鈕被點擊時,彈出此窗口 37 let alert = UIAlertController(title: "Information", message: "UIButton Event.", preferredStyle: UIAlertController.Style.alert) 38 //建立一個按鈕,做爲提示窗口中的【肯定】按鈕,當用戶點擊該按鈕時,將關閉提示窗口。 39 let OKAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil) 40 //將肯定按鈕,添加到提示窗口中 41 alert.addAction(OKAction) 42 //在當前視圖控制器中,展現提示窗口。 43 self.present(alert, animated: true, completion: nil) 44 } 45 46 override func didReceiveMemoryWarning() { 47 super.didReceiveMemoryWarning() 48 // Dispose of any resources that can be recreated. 49 } 50 }
在當前視圖控制器中,展現提示窗口,而後單擊資源文件夾,導入一張圖片,做爲按鈕的背景圖片post
【+】->【Import】->選擇圖片->【Open】字體