在我的UIButton中添加了一个带有子类的下拉三角形,当我更改标题时,如何防止它拉伸?

Dou*_*ith 1 cocoa-touch uibutton uiview ios swift

我有一个简单的UIButton子类,在默认的UIButtons中添加一个下拉三角形.我UIView在我的Storyboard中的视图控制器的标题视图中删除了一个,然后在Storyboard中将按钮子类添加到该视图中.我在故事板中使用自动布局的唯一方法是垂直和水平居中.

这是代码:

class DropDownButton: UIButton {   
    override func awakeFromNib() {
        super.awakeFromNib()

        setImage(UIImage(named: "drop-down-triangle"), forState: .Normal)

        sizeToFit()

        titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageRectForContentRect(bounds).width - 17.0, bottom: 0, right: 0)
        imageEdgeInsets = UIEdgeInsets(top: 0, left: titleRectForContentRect(bounds).width, bottom: -2, right: 0)
    }
}
Run Code Online (Sandbox Code Playgroud)

这是它的样子:

在此输入图像描述

在代码中,我有时会更改标题:

dropDownButton.setTitle(title, forState: .Normal)
Run Code Online (Sandbox Code Playgroud)

这导致它看起来像这样:

在此输入图像描述

是什么造成的?如何阻止它伸展?

has*_*san 6

class DropDownButton: UIButton {   
    override func awakeFromNib() {
        super.awakeFromNib()

        setImage(UIImage(named: "drop-down-triangle"), forState: .Normal)

        sizeToFit()

        titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageRectForContentRect(bounds).width - 17.0, bottom: 0, right: 0)
        imageEdgeInsets = UIEdgeInsets(top: 0, left: **static value here**, bottom: -2, right: 0)
    }
}
Run Code Online (Sandbox Code Playgroud)