swift 实践- 04 -- UIButton

import UIKit

class ViewController: UIViewController {

// 按钮的创建

// UIButtonType.system: 前面不带图标, 默认文字为蓝色,有触摸时的高亮效果

// UIButtonType.custom: 定制按钮,前面不带图标, 默认文字为白色,无触摸时的高亮

// UIButtonType.contactAdd: 前面带 + 图标按钮,默认文字蓝色,无触摸高亮

// UIButtonType.detailDisclosure: 前面带 ! 图标, 默认文字蓝色, 有触摸高亮

// UIButtonType.infoDark: 同上

// UIButtonType.infoLight: 同上

override func viewDidLoad() {

super.viewDidLoad()

let button:UIButton = UIButton(type: .custom)

button.frame = CGRect(x: 100, y: 100, width: 100, height: 100)

button.setTitle("按钮", for: .normal)

self.view.addSubview(button)

button.backgroundColor = UIColor.red

// 添加点击事件

button.addTarget(self, action: #selector(tapped), for: .touchUpInside)

button.addTarget(self, action: #selector(touchBtn(sender:)), for: .touchUpInside)

// button 文字太长 设置 titleLabel 的 lineBreakMode 属性 调整

button.titleLabel?.lineBreakMode = .byClipping

// lineBreakMode 共支持如下几种样式

// .byTruncatingHead: 省略头部文字, 省略部分用 ... 代替

// .byTruncatingMiddle: 省略中间部分文字

// .byTruncatingTail: 省略尾部文字

// .byClipping: 直接将多余的部分截断

// .byWordWrapping: 自动换行 (按词拆分)

// .byCharWrapping: 自动换行 (按字符拆分)

// 注意: 当设置自动换行后(byCharWrapping 或 byWordWrapping), 我们可以在设置 title 时通过添加 \n 进行手动换行

}

func tapped() {

print("测试")

}

func touchBtn(sender: UIButton) {

if let text = sender.titleLabel?.text {

print(text)

}

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

// Dispose of any resources that can be recreated.

}

}