UIButton用于“backgroundRect(forBounds :)”的方法是什么?

时间:2018-06-07 09:19:17

标签: swift uibutton cgrect

我发现UIButton有一个backgroundRect(forBounds:)函数,但我无法理解我在哪里以及如何使用它。

我也无法理解如何使用contentRect(forBounds:)titleRect(forContentRect:)imageRect(forContentRect:)方法。请解释一下。

2 个答案:

答案 0 :(得分:1)

默认情况下,backgroundRect(forBounds:)会将相同值作为bounds返回。但是,您可以在子类中覆盖它以防止绘制自定义内容。

来自Apple Developer Documentation

  

此方法的默认实现返回bo​​unds参数中的值。此矩形表示按钮绘制其标准背景内容的区域。提供自定义背景装饰的子类可以覆盖此方法并返回修改的边界矩形,以防止按钮覆盖任何自定义内容。

contentRect(forBounds:)返回用于显示标题和按钮图像的区域。

titleRect(forContentRect:)imageRect(forContentRect:)返回标题/图片的矩形。

以下是针对未覆盖的标准按钮的所有这四种方法的返回值的视觉帮助:

visual representation of the return value of the methods mentioned above

答案 1 :(得分:1)

  

但是我无法想象我需要解决这个问题的情况

然后想象一下:当用户的手指不再在按钮上时,作为对用户的反馈,响应于被轻敲而看起来缩小一点的按钮,回到正常大小。你会怎么做?这是一种优雅的方式:

extension CGSize {
    func sizeByDelta(dw:CGFloat, dh:CGFloat) -> CGSize {
        return CGSize(width:self.width + dw, height:self.height + dh)
    }
}
class MyShrinkingButton: UIButton {
    override func backgroundRect(forBounds bounds: CGRect) -> CGRect {
        var result = super.backgroundRect(forBounds:bounds)
        if self.isHighlighted {
            result = result.insetBy(dx: 3, dy: 3)
        }
        return result
    }
    override var intrinsicContentSize : CGSize {
        return super.intrinsicContentSize.sizeByDelta(dw:25, dh: 20)
    }
}

效果微妙但活泼清晰。这是处于正常状态并处于突出显示状态的按钮。

enter image description here enter image description here

相关问题