標籤:char pos idt res clip 支援 head create ide
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.
}
}
swift 實踐- 04 -- UIButton