UIKit - UIButton(按钮组件)

1.创建系统自带按钮


let btn = UIButton(type: .contactAdd)
    btn.frame = CGRect(x: 100, y: 105, width: 30, height: 30)
    self.view.addSubview(btn)

        /*
        UIButtonType.type有以下几种:
            system:前面不带图标,默认文字颜色为蓝色,有触摸时的高亮效果
            custom:定制按钮,前面不带图标,默认文字颜色为白色,无触摸时的高亮效果
            contactAdd:前面带“+”图标按钮,默认文字颜色为蓝色,有触摸时的高亮效果
            detailDisclosure:前面带“!”图标按钮,默认文字颜色为蓝色,有触摸时的高亮效
            infoDark:为感叹号“!”圆形按钮UIButtonType.infoLight:为感叹号“!”圆形按钮                           
        */

2.创建自定义按钮

let rect   = CGRect(x: 200, y: 100, width: 100, height: 40)
let button = UIButton(frame: rect)
        
    //设置按钮的文字
    button.setTitle("点击", for: .normal)
    self.view.addSubview(button)
        

3.修改按钮样式

//设置按钮标题样式
button.titleLabel?.font = UIFont(name: "Arial", size: 20)

//设置背景颜色
button.backgroundColor = UIColor.yellow

//设置背景图片
let bgImage = UIImage(named: "image1")
    button.setBackgroundImage(bgImage, for: .normal)


//设置圆角
button.layer.masksToBounds = true
button.layer.cornerRadius = 5
button.layer.borderWidth = 2
button.layer.borderColor = UIColor.blue.cgColor

4.设置按钮在不同状态下的样式

button.setTitle("点击", for: .normal)            //正常状态下文字    
button.setTitle("正在点击", for: .highlighted)    //高亮时文字
button.setTitle("获得焦点", for: .focused)        //获取焦点时文字
button.setTitle("按钮不可用", for: .disabled)        //不可用时文字
button.setTitle("按钮已选中", for: .selected)        //选中时文字

button.setTitleColor(UIColor.red, for: .normal)    //正常时标题颜色
button.setTitleColor(UIColor.darkGray, for: .selected)    //选中时标题颜色

5.为按钮添加点击事件

//是否禁止按钮使用
button.isEnabled = true    //true:可用(默认);false:禁止
        
//添加事件
button.addTarget(self, action: #selector(ViewController.buttonClick(_:)), for: UIControlEvents.touchUpInside)


//点击事件处理方法
func buttonClick(_ button:UIButton)
{
    NSLog("Button TouchInSide")
}

效果如果所示:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值