gpt4 book ai didi

ios - 使用子类向我的 UIButton 添加了一个下拉三角形,如何在更改标题时防止它拉伸(stretch)?

转载 作者:搜寻专家 更新时间:2023-11-01 06:10:17 24 4
gpt4 key购买 nike

我有一个简单的 UIButton 子类,用于向默认 UIButton 添加下拉三角形。我在 Storyboard 的 View Controller 的标题 View 中放置了一个 UIView,然后将按钮子类添加到 Storyboard 中的该 View 。我在 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

这是什么原因造成的?如何阻止它拉伸(stretch)?

最佳答案

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)
}
}

关于ios - 使用子类向我的 UIButton 添加了一个下拉三角形,如何在更改标题时防止它拉伸(stretch)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26987002/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com