I am trying to put an icon next to a button label.
Problem: Interface Builder puts the button-image not to the right side. So there is still some space next to the (x).
Thanks for your help
I am trying to put an icon next to a button label.
Problem: Interface Builder puts the button-image not to the right side. So there is still some space next to the (x).
Thanks for your help
You can do this in Interface Builder by setting the title and image insets:
In this case I've set the title right inset to 30 and the image left inset to 80. You can achieve the same in code by setting the UIButton
's imageEdgeInset
and titleEdgeInset
properties. Knowing the size of the UIButton's subviews, you could probably calculate the edge insets using something like this:
CGSize labelWidth = myButton.titleLabel.frame.size.width;
CGSize imageWidth = myButton.imageView.frame.size.width;
myButton.titleEdgeInsets = (UIEdgeInsets){0.0, -imageWidth, 0.0, imageWidth};
myButton.imageEdgeInsets = (UIEdgeInsets){0.0, labelWidth, 0.0, -labelWidth};
select image(if (x) is image) or title (if (x) is simply key) on the window and set left , Right offsets according to your need
i have achieved this:
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)
])
}
}
}
}