给UIButton设置不同状态下的背景色
生活随笔
收集整理的這篇文章主要介紹了
给UIButton设置不同状态下的背景色
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
系統給出的UIButton設置背景是通過設置setImage和setBackgroundImage的方法,需要提供不同的圖片素材。在開發中往往需要設置不同的純色背景的button,而且往往沒有圖片。于是只好選擇其他的方法了.以下的代碼可以解決這個問題。
extension UIButton {func setBackgroundColor(color: UIColor, forState: UIControl.State) {self.clipsToBounds = true // add this to maintain corner radiusUIGraphicsBeginImageContext(CGSize(width: 1, height: 1))if let context = UIGraphicsGetCurrentContext() {context.setFillColor(color.cgColor)context.fill(CGRect(x: 0, y: 0, width: 1, height: 1))let colorImage = UIGraphicsGetImageFromCurrentImageContext()UIGraphicsEndImageContext()self.setBackgroundImage(colorImage, for: forState)}} }總結
以上是生活随笔為你收集整理的给UIButton设置不同状态下的背景色的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 联想RS550服务器安装Ubuntu16
- 下一篇: 第七次作业(团队项目——Alpha阶段开