设置 button 中图片的大小
let closeBtn = UIButton.init(type: .system)
closeBtn.frame = CGRect(x: 0, y: 0, width: 66, height: 66);
closeBtn.setImage(#imageLiteral(resourceName: "arrow_down"), for: .normal)
closeBtn.tintColor = UIColor.white
closeBtn.imageEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
给按钮 绑定 长按事件
let btnDelete:UIButton = bomBtn();
btnDelete.setImage(#imageLiteral(resourceName: "delete"), for: .normal);
//绑定长按
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(KeyboardViewController.delLongPress(_:)))
longPress.minimumPressDuration = 0.5;//设置长按时间,默认0.5秒
longPress.numberOfTouchesRequired = 1;//点按的手指数
longPress.allowableMovement = 15;//允许多少像素内的活动
btnDelete.addGestureRecognizer(longPress)
func delLongPress(_ gestureRecognizer: UIGestureRecognizer) {
if gestureRecognizer.state == UIGestureRecognizerState.began{//保障只在按下的时候才执行
self.proxy.deleteBackward()
}
}
** 当 按下时 ,改 背景颜色 , 先准备一个全部是蓝色的 小尺寸bg_blue.png , 因为 会被拉伸,所以小点无所谓。
let x = UIButton()
x.setBackgroundImage(#imageLiteral(resourceName: "bg_blue"), for: .highlighted)
x.setTitle("我是Title", for: UIControlState.normal);
self.view.addSubview(x);
** 设置 title 显示的 偏移量
btn.titleEdgeInsets = UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 0) //= 向下移动10
** 自定义 按钮
class DiyBtn:UIButton{
var lb_1:UILabel!;
override init(frame: CGRect) {
super.init(frame: frame)
}
init(text:String,frame:CGRect) {
super.init(frame:frame);
lb_1 = UILabel(frame: frame);
lb_1.text = text;
lb_1.textAlignment = .center
lb_1.backgroundColor = UIColor.blue;
self.addSubview(lb_1)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
使用
let bt = DiyBtn(text: "我是标题", frame: CGRect(x: 80, y: 80, width: 120, height: 120))
self.view.addSubview(bt)
bt.lb_1.text = "我被修改了";
最终显示 “我被修改了"
** 获取点击位置
func mainBtnDrag(button:UIButton?,event:UIEvent){
let touch:UITouch = (event.touches(for: button!)?.first)!
let location = touch.location(in: self.view);
//location.x+","+location.y
}