我正在尝试在按钮标签旁边放置一个图标。
问题:Interface Builder将按钮图像放在右侧。因此(x)旁边仍有一些空间。
感谢您的帮助
答案 0 :(得分:7)
您可以通过设置title和image insets在Interface Builder中执行此操作:
在这种情况下,我将标题右侧插入设置为30 ,将图像左侧插入设置为80 。您可以通过设置UIButton
的{{1}}和imageEdgeInset
属性在代码中实现相同的功能。知道了UIButton子视图的大小,你可以用这样的东西来计算边缘插入:
titleEdgeInset
答案 1 :(得分:1)
答案 2 :(得分:0)
在窗口上选择图像(如果(x)是图像)或标题(如果(x)只是键)并向左设置,根据需要设置右偏移
答案 3 :(得分:-1)
我做到了:
class CustomButton: UIButton {
open var rightIcon: UIImage? {
didSet {
rightIconImage = UIImageView(image: rightIcon?.withRenderingMode(.alwaysTemplate))
rightIconImage?.tintColor = .white
if let rightIconImage = rightIconImage {
addSubview(rightIconImage)
}
layoutSubviews()
}
}
open override func layoutSubviews() {
super.layoutSubviews()
setupRightIconIfNeeded()
}
func setupRightIconIfNeeded() {
if let rightIconImage = rightIconImage {
rightIconImage.translatesAutoresizingMaskIntoConstraints = false
titleLabel?.translatesAutoresizingMaskIntoConstraints = false
if let titleLabel = titleLabel, titleLabel.frame.width > 0 {
let paddingLeft = (frame.width - titleLabel.frame.width - spacing - iconSize) / 2
NSLayoutConstraint.deactivate(constraints)
NSLayoutConstraint.deactivate(titleLabel.constraints)
NSLayoutConstraint.activate([
//set height constraint for button
heightAnchor.constraint(equalToConstant: apolloSize.height),
//set constraint for title label
titleLabel.widthAnchor.constraint(equalToConstant: titleLabel.frame.width),
titleLabel.heightAnchor.constraint(equalToConstant: titleLabel.frame.height),
titleLabel.centerYAnchor.constraint(equalTo: centerYAnchor),
titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: paddingLeft),
//set constraint for right icon
rightIconImage.leadingAnchor.constraint(equalTo: titleLabel.trailingAnchor, constant: spacing),
rightIconImage.centerYAnchor.constraint(equalTo: titleLabel.centerYAnchor),
rightIconImage.widthAnchor.constraint(equalToConstant: iconSize),
rightIconImage.heightAnchor.constraint(equalToConstant: iconSize)
])
}
}
}
}