Swift - UIButton

mport UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //创建Button类型:system,custom,contactAdd,(detailDisclosure,infoDark,infoLight效果一样),roundedRect
        let button = UIButton(type: .custom)
        //设置Button位置
      button.frame = CGRect(x: 150, y: 250, width: 100, height: 100)
        //设置按钮文字
        button.setTitle("按钮", for: .highlighted)//有三种状态:普通状态:normal,触摸状态:hightlighted禁用状态:disabled
        //设置按钮文字
        button.setTitleColor(UIColor.black, for: .normal)//有三种状态
        //设置按钮文字阴影
        button.setTitleShadowColor(UIColor.gray, for: .normal)
        //设置按钮字体和大小
        button.titleLabel?.font = UIFont.systemFont(ofSize:11)//系统字体
        button.titleLabel?.font = UIFont(name: "Farah", size: 11)//自定义字体
        //设置按钮背景颜色
        button.backgroundColor = UIColor.orange
        //设置按图案(如果自定义图标就不需要设置Button类型)
        button.setImage(UIImage(named:"icon"), for: .normal)
        button.adjustsImageWhenHighlighted = false//使触摸模式下按钮图标也不会变半透明
        button.adjustsImageWhenDisabled = false//是触摸模式下按钮图标也不会变半透明
        //保留图案本色(当Button类型为custom时无需次代码)
        let image = UIImage(named: "icon")?.withRenderingMode(.alwaysOriginal)
        button.setImage(image, for: .normal)
        //设置按钮背景图片
        button.setBackgroundImage(UIImage(named: "Image"), for: .normal)
        //按钮文字过长处理方法
        button.titleLabel?.lineBreakMode = .byClipping//其他处理方法详情请看Label章节
        //按钮触摸点击事件
        button.addTarget(self, action: #selector(ViewController.TapButton), for: .touchUpInside)
//        touchDown:单点触摸按下事件,点触屏幕
//        touchDownRepeat:多点触摸按下事件
//        touchDragInside:触摸在控件内拖动时
//        touchDragOutside:触摸在控件外拖动时
//        touchDragEnter:触摸从控件之外拖动到内部时
//        touchDragExit:触摸从控件内部拖动到外部时
//        touchUpInside:在控件之内触摸并抬起事件
//        touchUpOutside:在控件之外触摸抬起事件
//        touchCancel:触摸取消事件,即一次触摸因为放上太多手指而被取消,或者电话打断
        
        //添加Button到视图中
        self.view.addSubview(button)

    }
    @objc func TapButton()
    {
        print("你点击了此按钮")
    }
    
}

猜你喜欢

转载自www.cnblogs.com/iOS-Development/p/10227390.html