
| 1234567 | //創建一個ContactAdd類型的按鈕let button:UIButton = UIButton(type:.contactAdd)//設置按鈕位置和大小button.frame = CGRect(x:10, y:150, width:100, height:30)//設置按鈕文字button.setTitle("按鈕", for:.normal)self.view.addSubview(button) |
| 1 | let button = UIButton(frame:CGRect(x:10, y:150, width:100, height:30)) |
| 123 | button.setTitle("普通狀態", for:.normal) //普通狀態下的文字button.setTitle("觸摸狀態", for:.highlighted) //觸摸狀態下的文字button.setTitle("禁用狀態", for:.disabled) //禁用狀態下的文字 |
| 123 | button.setTitleColor(UIColor.black, for: .normal) //普通狀態下文字的顏色button.setTitleColor(UIColor.green, for: .highlighted) //觸摸狀態下文字的顏色button.setTitleColor(UIColor.gray, for: .disabled) //禁用狀態下文字的顏色 |
| 123 | button.setTitleShadowColor(UIColor.green, for:.normal) //普通狀態下文字陰影的顏色button.setTitleShadowColor(UIColor.yellow, for:.highlighted) //普通狀態下文字陰影的顏色button.setTitleShadowColor(UIColor.gray, for:.disabled) //普通狀態下文字陰影的顏色 |
| 1 | button.titleLabel?.font = UIFont.systemFont(ofSize: 11) |
| 1 | button.backgroundColor = UIColor.black |

| 123 | button.setImage(UIImage(named:"icon1"),forState:.Normal) //設置圖標button.adjustsImageWhenHighlighted=false //使觸摸模式下按鈕也不會變暗(半透明)button.adjustsImageWhenDisabled=false //使禁用模式下按鈕也不會變暗(半透明) |

| 1234 | let iconImage = UIImage(named:"icon2")?.withRenderingMode(.alwaysOriginal)button.setImage(iconImage, for:.normal) //設置圖標button.adjustsImageWhenHighlighted = false //使觸摸模式下按鈕也不會變暗(半透明)button.adjustsImageWhenDisabled = false //使禁用模式下按鈕也不會變暗(半透明) |

| 1 | button.setBackgroundImage(UIImage(named:"bg1"), for:.normal) |
| 123456789101112 | //不傳遞觸摸對象(即點擊的按鈕)button.addTarget(self, action:#selector(tapped), for:.touchUpInside)func tapped(){ PRint("tapped")} //傳遞觸摸對象(即點擊的按鈕),需要在定義action參數時,方法名稱后面帶上冒號button.addTarget(self, action:#selector(tapped(_:)), for:.touchUpInside) func tapped(_ button:UIButton){ print(button.title(for: .normal))} |
新聞熱點
疑難解答