Set the size of the image in the 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)
Bind the long press event to the button
let btnDelete:UIButton = bomBtn(); btnDelete.setImage(#imageLiteral(resourceName: "delete"), for: .normal); //Bind long press let longPress = UILongPressGestureRecognizer(target: self, action: #selector(KeyboardViewController.delLongPress(_:))) longPress.minimumPressDuration = 0.5;//Set the long press time, the default is 0.5 seconds longPress.numberOfTouchesRequired = 1;//The number of fingers to click longPress.allowableMovement = 15;//How many pixels are allowed within the activity btnDelete.addGestureRecognizer(longPress)
func delLongPress(_ gestureRecognizer: UIGestureRecognizer) { if gestureRecognizer.state == UIGestureRecognizerState.began{//Ensure that it is only executed when pressed self.proxy.deleteBackward() } }
** When pressed, change the background color, first prepare a small size bg_blue.png that is all blue, because it will be stretched, so the small point does not matter.
let x = UIButton() x.setBackgroundImage(#imageLiteral(resourceName: "bg_blue"), for: .highlighted) x.setTitle("我是Title", for: UIControlState.normal); self.view.addSubview(x);
** Set the offset of title display
btn.titleEdgeInsets = UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 0) //= move down 10
** custom button
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") } }
use
let bt = DiyBtn(text: "I am the title", frame: CGRect(x: 80, y: 80, width: 120, height: 120)) self.view.addSubview(bt) bt.lb_1.text = "I have been modified";
Eventually it says "I have been modified"