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

前提是你 提交于 2020-04-13 19:56:27

问题


Large accessibility font size for UIButton title (.body or .headline) does not increase the frame of button but only increase the title text. It can clearly be seen in the screenshot below:

Constraints are only top, leading and trailing, also in code I have added 2 lines:

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

The yellow background colour is of the button, thus identifying that only tappable area is the yellow area. I want to increase the button frame so that the whole text area becomes tappable.


回答1:


There is an issue with multi-line button labels to begin with - I don't think it's directly related to using accessibility fonts.

Try using this button subclass:

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
    }
}

It sets the titleLable's .numberOfLines = 0, .textAlignment = .center, and hugging priorities, and then override's intrinsicContentSize to tell auto-layout the proper size of the titleLabel.




回答2:


Possible solution is :

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


来源:https://stackoverflow.com/questions/57587105/uibutton-frame-does-not-increase-with-accessibility-large-font-using-swift-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!