可以左对齐按钮文本但右对齐背景或按钮图像?

时间:2018-03-26 22:02:44

标签: ios objective-c uibutton

您好我在故事板中创建了UIButton,我希望左对齐标题但右对齐图像。到目前为止,我一直无法找到办法。我知道可以添加一个单独的UIImage,但为了简化自动布局,我希望用一个按钮完成所有操作。

在故事板或代码中这样的事情是否可能?提前感谢任何建议

3 个答案:

答案 0 :(得分:1)

在子类中覆盖它:

- (CGRect)titleRectForContentRect:(CGRect)contentRect;
- (CGRect)imageRectForContentRect:(CGRect)contentRect;

然后在故事板中使用此子类

答案 1 :(得分:1)

我的UIButton扩展方法,在Swift中。抱歉,它不是obj-c。我的项目现在几乎由Swift编写。

extension UIButton {
    // ## Usage
    // let btn: UIButton = //... UIButton
    //
    // ... configure `image` and `text` before calling following method. 
    // btn.myImageRightAligned()
    // Let image of `UIButton` aligned right. 

    public func myImageRightAligned(_ spacing: CGFloat = 2.0) {
        let button = self
        guard (button.imageView != nil && button.imageView?.image != nil) else {
            return
        }
        guard (button.titleLabel != nil && button.titleLabel?.text != nil) else {
            return
        }
        let imageSize = button.imageView!.image!.size
        let title = button.titleLabel!.text! as NSString
        let titleSize = title.size(attributes: [NSFontAttributeName: button.titleLabel!.font])

        button.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: -(imageSize.width + spacing), bottom: 0.0, right: imageSize.width)
        button.imageEdgeInsets = UIEdgeInsets(top: 0.0, left:  titleSize.width, bottom: 0.0, right: -(titleSize.width + spacing))

        self.setNeedsLayout()
    }
}

答案 2 :(得分:0)

您可以在故事板中从元素检查器更改按钮图像偏移(更改位置),我没有得到对齐背景的含义,因为它覆盖了整个按钮,此处没有左右任何

相关问题