简体   繁体   中英

adjust font size to width on dynamically resizing button, button doesn't have a width static constraint

I have three buttons that end up pretty close together when in iPad adaptability mode, but then far apart when in iPad or iPhone landscape. I have the buttons scale correctly using static trailing/leading/bottom space constraints and their height is set proportional to the view height. The buttons resize nicely but I have to set all the button label font sizes programmatically for different screen sizes in viewdidload. I was hoping I could add resizable title labels functionality in my class but I cant seem to lock it in.

Any help would be appreciated.

My custom button class:

    import UIKit

class BetterButton: UIButton {

required public init?(coder aDecoder: NSCoder) {

    super.init(coder: aDecoder)

    self.titleLabel!.font = UIFont(name: "Marker Comp", size: 200)
    self.titleLabel?.minimumScaleFactor = 0.5
    self.titleLabel?.numberOfLines = 0
    self.titleLabel?.adjustsFontSizeToFitWidth = true

    self.layer.cornerRadius = 4
    self.layer.shadowOpacity = 1
    self.layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
    self.layer.shadowRadius = 0
    self.layer.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.25).cgColor

}

}

All the buttons text is at 200 at runtime, but the adjust to width doesn't activate.

Try adding this:

self.titleLabel?.lineBreakMode = NSLineBreakMode.ByClipping

Also, font size of 200 with a minimumScaleFactor of 0.5 results in a smallest font size of 100, which is still pretty darn big.

Changing minimumScaleFactor to 0.1 or 0.05, or changing max / normal font size to something like 30 will do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM