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

时间:2014-11-18 05:09:27

标签: ios cocoa-touch swift uiview uibutton

我有一个简单的UIButton子类,可以在默认的UIButtons中添加一个下拉三角形。我在我的Storyboard中的视图控制器的标题视图中删除UIView,然后在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)
    }
}

这就是它的样子:

enter image description here

在代码中,我有时会用以下内容更改标题:

dropDownButton.setTitle(title, forState: .Normal)

导致它看起来像这样:

enter image description here

造成这种情况的原因是什么?如何阻止它伸展?

2 个答案:

答案 0 :(得分: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)
    }
}

答案 1 :(得分:-1)

如果您使用的是故事板,请按屏幕截图所示设置属性。或者您可以以编程方式设置它们。

在代码中你可以像这样使用:

[privacyButton setImage:[UIImage imageNamed:@"arrow_up.png"] forState:UIControlStateNormal];

[privacyButton setImage:[UIImage imageNamed:@"arrow_down.png"] forState:UIControlStateNormal];

希望这会有所帮助。enter image description here