简体   繁体   中英

How to disable the title of UIButton shifiting to right when an image is added to the button?

I have created a custom UIButton class to show the image of the button at the right edge of the screen.

The code is as follows -

class CutomButton: UIButton {    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    func setup() {
        imageView?.translatesAutoresizingMaskIntoConstraints = false
        imageView?.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8).isActive = true
        imageView?.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
    }
}

The above code works as expected. However, the title of the button moves to the right as if the imageView was in its original position (to the left of the title).

Can anyone point out how the title of the button can be placed to its original position as if the image of the button is not present?

By default the UIButton class manages this internally but you do have a few options:

Easy Mode: Modify the edge insets defined in the UIButton: titleEdgeInsets and imageEdgeInsets . Look at a different SO post for a previous answer that is similar enough but you will just have to modify it for your needs.

Advanced (but more flexible) Mode: Since you are creating a subclass, you could instead subclass UIControl instead of UIButton . Since UIButton IS a subclass of UIControl, touch events are still registered in the same manner as a UIButton and you can override the isHighlighed/isSelected to control the way the "custom button" looks in the touched state.

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