UIButton 框架不会随着使用 Swift 5 的可访问性大字体而增加

UIButton frame does not increase with accessibility large font using Swift 5

UIButton 标题(.body 或 .headline)的大字体大小不会增加按钮的框架,只会增加标题文本。在下面的截图中可以清楚地看到:

约束只有顶部、前导和尾部,同样在代码中我添加了 2 行:

button.adjustsImageSizeForAccessibilityContentSizeCategory = true
button.titleLabel?.numberOfLines = 0

按钮的底色为黄色,从而标识唯一可点击区域为黄色区域。我想增加按钮边框,使整个文本区域都可以点击。

可能的解决方案是:

button.titleLabel?.numberOfLines = 0
button.titleLabel?.lineBreakMode = .byWordWrapping
button.titleLabel?.masksToBounds = true
button.sizeToFit()

首先是多行按钮标签存在问题 - 我认为这与使用辅助字体没有直接关系。

尝试使用此按钮子类:

class MultilineTitleButton: UIButton {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    func commonInit() -> Void {
        self.titleLabel?.numberOfLines = 0
        self.titleLabel?.textAlignment = .center
        self.setContentHuggingPriority(UILayoutPriority.defaultLow + 1, for: .vertical)
        self.setContentHuggingPriority(UILayoutPriority.defaultLow + 1, for: .horizontal)
    }

    override var intrinsicContentSize: CGSize {
        let size = self.titleLabel!.intrinsicContentSize
        return CGSize(width: size.width + contentEdgeInsets.left + contentEdgeInsets.right, height: size.height + contentEdgeInsets.top + contentEdgeInsets.bottom)
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        titleLabel?.preferredMaxLayoutWidth = self.titleLabel!.frame.size.width
    }
}

它设置 titleLable 的 .numberOfLines = 0.textAlignment = .center 和拥抱优先级,然后覆盖 intrinsicContentSize 以告诉自动布局 titleLabel 的正确大小。