Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

https://www.dropbox.com/s/b62dz7f0qvw8tf4/Screenshot%202019-08-21%20at%2012.48.16%20PM.png?dl=0

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.

like image 903
Mumtaz Hussain Avatar asked Mar 03 '23 13:03

Mumtaz Hussain


1 Answers

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.

like image 81
DonMag Avatar answered Apr 29 '23 16:04

DonMag