[英]UIButton with title and image
I need a button with an image inside of it and a text under the button. 我需要一个带有图像的按钮,并在按钮下方有一个文本。 I can't use the image as a background because it would stretch the image.
我不能将图像用作背景,因为它会拉伸图像。 So my problem is if I use an image for the button, the title will be covered by the image.
所以我的问题是,如果我在按钮上使用图片,标题将被图片覆盖。 Is there any solution for this?
有什么解决办法吗?
Here is an example how it should look like at the end: 这是一个示例,最后看起来应该是怎样的:
Change Title and Image Insets 更改标题和图像插图
also change control Vertical to bottom 也将控制从垂直更改为底部
You could make a separate UIImage and UILabel at the positions you prefer, and cover them with transparent UIButton. 您可以在您喜欢的位置制作一个单独的UIImage和UILabel,并用透明的UIButton覆盖它们。 That should do the trick.
这应该够了吧。
Hope it helps. 希望能帮助到你。
您可以继承UIButton并重新定义layoutSubviews方法。
You can adjust the following properties of UIButton
: var titleEdgeInsets: UIEdgeInsets
, var imageEdgeInsets: UIEdgeInsets
. 您可以调整
UIButton
的以下属性: var titleEdgeInsets: UIEdgeInsets
, var imageEdgeInsets: UIEdgeInsets
。
Another way of doing this is subclassing UIControl
. 做到这一点的另一种方法是子类化
UIControl
。 It's a UIView
subclass that is meant to be used for such cases. 这是一个
UIView
子类,旨在用于此类情况。 UIButton
is a subclass of UIControl
for example. UIButton
是UIControl
的子类。 That way you have more control over the layout and you don't need to fight UIButton
's builtin behaviour. 这样一来,您可以更好地控制布局,而无需
UIButton
的内置行为。
You can do your layout either in code or with Interface Builder in a xib
file. 您可以使用代码或使用
xib
文件中的Interface Builder进行xib
。
class MyButton: UIControl {
var imageView: UIImageView
var label: UILabel
// adjust colors for changed states like highlighting, etc.
override var isHighlighted: Bool {
didSet {
if isHighlighted {
backgroundColor = UIColor.grey
} else {
backgroundColor = UIColor.white
}
}
}
override var isSelected: Bool { didSet { ... } }
override var isEnabled: Bool { didSet { ... } }
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
override init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
imageView = UIImageView(image: UIImage(...))
addSubView(imageView)
label = UILabel(frame: CGRect(...))
addSubView(label)
// TODO: add constraints for layout
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.