简体   繁体   中英

UIButton auto-adjust Button font size Swift

I try to make out some quiz and have a problem with my answer buttons. Simple fact: The text is too long and I try to auto-adjust it for cells using different methods. My current status:

        for btn in btnArr{
        btn.titleLabel!.minimumScaleFactor = 0.3
        btn.titleLabel!.numberOfLines = 0
        btn.titleLabel!.adjustsFontSizeToFitWidth = true
        btn.titleLabel?.baselineAdjustment = UIBaselineAdjustment.AlignCenters
        //btn.contentEdgeInsets = UIEdgeInsets(top: 3.0,left: 3.0,bottom: 3.0,right: 3.0)
    }

I hope somebody has another option for me to make that work :)

Regards, Patrick

EDIT:

 self.view.addConstraint(NSLayoutConstraint(item: btn.titleLabel!, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: btn, attribute:NSLayoutAttribute.Height, multiplier: 0.99, constant: 0))  

With auto layout you can set the space between buttons, and the max and min size. In code for all labels use:

self.button.titleLabel.numberOfLines = 0;
self.button.titleLabel.adjustsFontSizeToFitWidth = YES;

With this all labels adjust the text will size.

For adjust button to titleLabel use auto layout constraint for titleLabel. For examples:

  [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.button.titleLabel
                                                          attribute:NSLayoutAttributeHeight
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:self.view
                                                          attribute:NSLayoutAttributeHeight
                                                         multiplier:0.5
                                                           constant:0]];

This constraint define the height of titleLabel to 50% of self.view height. Now you can adapte the constraint for that you need.

This work in you code?

假设单元格的高度和字体相同,则可以通过将“ numberOfLines”设置为非0的值(例如3或4)来限制文本。

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