OGeek|极客世界-中国程序员成长平台

标题: ios - 右侧图像的按钮从右侧对齐 x 点 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 14:05
标题: ios - 右侧图像的按钮从右侧对齐 x 点

我正在尝试创建一个如下所示的按钮:

enter image description here

所以它有一个边框和一个右 ImageView 。

我这样子类化 UIButton:

class ButtonWithRightImage: UIButton {

    override func imageRectForContentRect(contentRect:CGRect) -> CGRect {
        var imageFrame = super.imageRectForContentRect(contentRect)
        imageFrame.origin.x = CGRectGetMaxX(super.titleRectForContentRect(contentRect)) - CGRectGetWidth(imageFrame)
        return imageFrame
    }

    override func titleRectForContentRect(contentRect:CGRect) -> CGRect {
        var titleFrame = super.titleRectForContentRect(contentRect)
        if (self.currentImage != nil) {
            titleFrame.origin.x = CGRectGetMinX(super.imageRectForContentRect(contentRect))
        }
        return titleFrame
    }
}

我按如下方式创建了我的按钮:

lazy var testButton: ButtonWithRightImage = {
   let button = ButtonWithRightImage(forAutoLayout: ())

    button.setTitle("rivacy", forState: .Normal)
    button.setTitleColor(UIColor.DarkBlue(), forState: .Normal)

    button.layer.borderWidth = 1
    button.layer.borderColor = UIColor.grey().CGColor

    button.setImage(UIImage(named: "arrow"), forState: .Normal)

    button.contentHorizontalAlignment = .Left
    button.contentEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0)

    return button
}()

现在我的按钮看起来像这样:

enter image description here

如您所见,图像未与右侧 20 点对齐。 我不知道该怎么做。我正在使用自动布局来显示按钮,所以我不能只修改我猜的框架。



Best Answer-推荐答案


由于您的 ButtonWithRightImage 类需要修改以根据您的要求实现输出。

class ButtonWithRightImage: UIButton {

    override func imageRectForContentRect(contentRect:CGRect) -> CGRect {
        var imageFrame = super.imageRectForContentRect(contentRect)
        imageFrame.origin.x = CGRectGetWidth(contentRect) - CGRectGetWidth(imageFrame)
        return imageFrame
    }

    override func titleRectForContentRect(contentRect:CGRect) -> CGRect {
        var titleFrame = super.titleRectForContentRect(contentRect)
        if (self.currentImage != nil) {
            titleFrame.origin.x = CGRectGetMinX(super.imageRectForContentRect(contentRect))
        }
        return titleFrame
    }
}

问题是您需要从 容器宽度 中减去图像宽度。而不是 container maxX 值。

如果您对此有任何意见,请告诉我。

谢谢

关于ios - 右侧图像的按钮从右侧对齐 x 点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39545159/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4