简体   繁体   English

当将图像添加到按钮时,如何禁用UIButton的标题调整?

[英]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. 我创建了一个自定义UIButton类,以在屏幕的右边缘显示按钮的图像。

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). 但是,按钮的标题向右移动,就像imageView处于其原始位置一样(位于标题的左侧)。

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: 默认情况下, UIButton类在内部进行管理,但您确实有一些选择:

Easy Mode: Modify the edge insets defined in the UIButton: titleEdgeInsets and imageEdgeInsets . 简易模式:修改在UIButton中定义的边插入: titleEdgeInsetsimageEdgeInsets 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. 在不同的SO帖子中查找先前的答案,该答案足够类似,但您只需根据需要进行修改即可。

Advanced (but more flexible) Mode: Since you are creating a subclass, you could instead subclass UIControl instead of UIButton . 先进(但更灵活)模式:由于正在创建子类,因此可以代替UIControl而不是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. 由于UIButton是UIControl的子类,因此触摸事件仍以与UIButton相同的方式注册,并且您可以覆盖isHighlighed / isSelected以控制“自定义按钮”在触摸状态下的显示方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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