目录:[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】字体