简体   繁体   中英

UIButton UIEdgeInsets doesn't work

So I've looked at all projects on Stack Overflow for adding edge insets for UIImages in a UIButton but none of them worked. When I build the project, the image is just set through the bounds of the button - it's not set to the insets and I don't know why. Here is the code:

let Settingsbutton = AnimatableButton(frame: CGRect(x: 23, y: 30, width: 40, height: 40))
    Settingsbutton.layer.cornerRadius = Settingsbutton.frame.size.height / 2
    Settingsbutton.layer.backgroundColor = UIColor.white
    let roundedButton3 = UIButton(type: .custom)
    roundedButton3.frame = Settingsbutton.frame
    let _border3 = CAShapeLayer()
    _border3.path = UIBezierPath(roundedRect: roundedButton3.bounds, cornerRadius:roundedButton3.frame.size.width/2).cgPath
    _border3.frame = roundedButton3.bounds
    _border3.strokeColor = UIColor.white.cgColor
    _border3.fillColor = UIColor.clear.cgColor
    _border3.lineWidth = 3.0

    Settingsbutton.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10)
    Settingsbutton.contentVerticalAlignment = .fill
    Settingsbutton.contentHorizontalAlignment = .fill
    Settingsbutton.layer.addSublayer(_border3)
    self.view.addSubview(Settingsbutton)
    self.view.bringSubview(toFront: Settingsbutton)

    if PFUser.current() == nil{
        Settingsbutton.setBackgroundImage(UIImage(named: "padlock"), for: .normal)

    }else{

    }

imageEdgeInsets are for positioning the image NOT the background image!

Use setImage instead of setBackgroundImage

If AnimatableButton is a UIButton why you want to add button inside button? I don't know really what's your purpose but you might try Settingsbutton.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM