
| 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))} |
新闻热点
疑难解答