swift -> 按钮(UIButton)

 设置 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
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值