UIButton swift版

前言

UIButton与用户的交互非常频繁,用户处理各种触摸事件
继承链:UIButton — UIControl

属性及其方法

    lazy private var testButton: UIButton = {
        //初始化方法,一般都使用第二种。然后样式的话基本上也都是自定义,根据需要用什么添加什么
//        let button: UIButton = UIButton(frame: <#T##CGRect#>)
        let button: UIButton = UIButton(type: .custom)
        //contactAdd类型为 + 号;infoLight 为亮蓝色的感叹号;infoDark为暗蓝色感叹号。不过这些都可以自定义实现
        
        button.backgroundColor = UIColor.red
        button.setTitle("123", for: .normal)    //设置按钮的标题集对应的状态,按钮的标题可能会有多个,每种状态都可以有一种标题
        button.setTitle("456", for: .highlighted)
        button.setTitleColor(UIColor.white, for: .normal)   //设置某种状态下标题的颜色
        button.setTitleColor(UIColor.blue, for: .highlighted)

        button.setTitleShadowColor(UIColor.black, for: .normal)   //设置标题阴影的颜色
        button.reversesTitleShadowWhenHighlighted = true    //按钮突出显示时标题阴影是否更改,默认false

        button.setImage(UIImage(named: "ocr_contrast_blue1"), for: .normal) //根据按钮的状态设置图片
        button.setImage(UIImage(named: "ocr_contrast_blue0"), for: .highlighted)

        button.adjustsImageWhenHighlighted = false   //图像在高亮状态下也会高亮显示,默认为true,只针对背景图片
        button.adjustsImageWhenDisabled = true      //禁用按钮的时候颜色变暗
        button.isEnabled = true                     //禁用按钮

//        print("\(button.preferredSymbolConfigurationForImage(in: .normal))")

        button.contentEdgeInsets = UIEdgeInsets(top: 5, left: 20, bottom: 5, right: 20)     //设置内边距
        button.titleEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 35)        //设置标题的内边距
        button.imageEdgeInsets = UIEdgeInsets(top: 35, left: 5, bottom: 5, right: 5)        //设置图像的内边距

        print("\(String(describing: button.currentTitle))")                 //获取当前按钮上的文本
        print("\(String(describing: button.currentAttributedTitle))")       //获取当前按钮上的富文本
        //还有一些获取图片,背景图片,阴影颜色等等也都一样

        //下面这四个属性需要通过重写实现;可以改变内容、标题、图像的位置
        print("\(button.backgroundRect(forBounds: button.bounds))")
        print("\(button.contentRect(forBounds: button.bounds))")
        print("\(button.titleRect(forContentRect: button.bounds))")
        print("\(button.imageRect(forContentRect: button.bounds))")
        
        button.addTarget(self, action: #selector(buttonClick), for: .touchUpInside) //按钮的手势有很多种,在这里是用的单击
        
        return button
    }()
    
    @objc func buttonClick() {
        self.testButton.backgroundColor = UIColor.blue
    }

相关问题总结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值