如何调整FontSizeToFitWidth到UIButton标签? IOS

时间:2016-01-20 09:59:31

标签: ios uibutton uilabel uiedgeinsets

当我将adjustsFontSizeToFitWidth设置为按钮UILabel时,文本出现在按钮框的一侧,我不知道为什么?

这是我的代码:

            shareBtn = UIButton()

            shareBtn.setTitle(IconsConstants.share, forState: UIControlState.Normal)
            shareBtn.titleLabel?.font = UIFont.iconmoonFont(100)
            shareBtn.titleLabel?.adjustsFontSizeToFitWidth = true;
            shareBtn.contentVerticalAlignment = UIControlContentVerticalAlignment.Center
            shareBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Center


            //EdgeInsets

            shareBtn.contentEdgeInsets = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10)

以下是结果:

enter image description here

1 个答案:

答案 0 :(得分:0)

单行设置

shareBtn.titleLabel?.adjustsFontSizeToFitWidth = YES;

而不是

factLabel.adjustsFontSizeToFitWidth = true;

多行我们使用

actLabel.numberOfLines = 0;
factLabel.lineBreakMode = NSLineBreakByWordWrapping;
CGSize maximumLabelSize = CGSizeMake(factLabel.frame.size.width, CGFLOAT_MAX);
CGSize expectSize = [factLabel sizeThatFits:maximumLabelSize];
factLabel.frame = CGRectMake(factLabel.frame.origin.x, factLabel.frame.origin.y, expectSize.width, expectSize.height);