let buttonMy : UIButton = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
self.view .addSubview(buttonMy)
buttonMy.backgroundColor = UIColor.red
//设置文字
buttonMy.setTitle("普通状态", for: .normal)
buttonMy.setTitle("高亮状态", for: .highlighted)
buttonMy.setTitle("禁用状态", for: .disabled)
//设置按钮文字比较长显示不完情况下的处理
buttonMy.titleLabel?.lineBreakMode = .byTruncatingTail
//设置文字颜色
buttonMy.setTitleColor(UIColor.white, for: .normal)
//设置按钮图片
buttonMy.setBackgroundImage(UIImage(named: "gougou.jpg"), for: .normal)
buttonMy.setImage(UIImage(named: "图片名"), for: .normal)
//设置按钮的文字和图片偏移量
buttonMy.titleEdgeInsets = UIEdgeInsets.init(top: -5, left: -10, bottom: 0, right: 0)
buttonMy.imageEdgeInsets = UIEdgeInsets.init(top: 1, left: 2, bottom: 0, right: 1)
//给按钮添加点击事件
/*
touchDown:单点触摸按下事件,点触屏幕
touchDownRepeat:多点触摸按下事件,点触计数大于1,按下第2、3或第4根手指的时候
touchDragInside:触摸在控件内拖动时
touchDragOutside:触摸在控件外拖动时
touchDragEnter:触摸从控件之外拖动到内部时
touchDragExit:触摸从控件内部拖动到外部时
touchUpInside:在控件之内触摸并抬起事件
touchUpOutside:在控件之外触摸抬起事件
touchCancel:触摸取消事件,即一次触摸因为放上太多手指而被取消,或者电话打断
*/
buttonMy.addTarget(self, action: #selector(buttonClick1), for: .touchUpInside)
buttonMy.addTarget(self, action: #selector(buttonClick2 (button01:)), for: .touchUpInside)
下面是点击按钮方法的实现
@objc func buttonClick1 () {
print("你点击了我这个按钮方法buttonClick1");
}
@objc func buttonClick2 (button01:UIButton) {
print("你点击了我这个按钮方法buttonClick2(buttonMy:)");
}
网友评论