2016-02-16 68 views
0

此图片显示了我想要实现:配件按钮上的文字大小,以匹配按钮大小

enter image description here

我指定的2个按钮的宽度是相同的0.4 * redViewWidth和高度0.8 * redViewheight。比我想要的文字大小为2行,尽可能大,仍然适合按钮框架。我正在使用自定义字体并且没有自动布局。令我惊讶的是,这并没有发生。该文本是在2行,但文字字体太大,并明确不适合按钮大小。我哪里做错了?

编辑:redView使用自动布局。用按钮填充redView不使用。

let font = UIFont(name: "customfont", size: 19) 
    button1 = UIButton() 
    button2 = UIButton() 

    button1.frame = CGRectMake(navigationBarView.frame.width*0.6, navigationBarView.frame.height*0.1, navigationBarView.frame.width*0.4, navigationBarView.frame.height*0.8) 
    button2.frame = CGRectMake(navigationBarView.frame.width*0.2, navigationBarView.frame.height*0.1, navigationBarView.frame.width*0.4, navigationBarView.frame.height*0.8) 


    button1.setTitle("button2\ntext text text text", forState: UIControlState.Normal) 
    button1.titleLabel?.textAlignment = NSTextAlignment.Center 
    button1.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping 
    button1.titleLabel?.font=font 
    button1.titleLabel?.adjustsFontSizeToFitWidth=true 
    button1.titleLabel?.minimumScaleFactor = 0.1 
    button2.setTitle("button1\ntext text text text", forState: UIControlState.Normal) 
    button2.titleLabel?.textAlignment = NSTextAlignment.Center 
    button2.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping 
    button2.titleLabel?.font=font 
    button2.titleLabel?.adjustsFontSizeToFitWidth=true 
    button2.titleLabel?.minimumScaleFactor = 0.1 

回答

0

你需要指定的UILabel行数如下:

button1.titleLabel?.numberOfLines = 2 
button2.titleLabel?.numberOfLines = 2 

编辑: 从Dynamically changing font size of UILabel 两者显然,自动调整大小的标签的字体大小,当你有一个单行只能。下面的代码会自动调整UILabel的大小,并且应该足够简单,以便为UIButton进行编辑(但是,这在Objective-C中)。

与iOS7开始,sizeWithFont变得过时。多行的情况下减少到:

factLabel.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); 
+0

其实,标题标签在2行中已经有了这个意思。问题是文本字体大小不调整以匹配按钮的框架。 – brumbrum

+0

看看编辑,另一种方法是遍历字体大小,并检查每个字体的lineHeight属性,虽然这看起来有点怪异。 –

+0

感谢您的阻止。请原谅我,如果我误解了代码..我认为这会改变按钮框架,以适应其标题中的任何文本。在我的情况下,框架是固定的 - 总是0.4 * redViewWidth。这是需要改变以考虑iOS设备的不同屏幕的字体大小。 – brumbrum

0

我结束了这样的事情。它会检查屏幕宽度并相应地分配字体大小。硬编码,但它诀窍。

let screenRect = UIScreen.mainScreen().bounds 
     let screenWidth = screenRect.size.width; 

var fontSize = 15 
     if screenWidth>410{ 
      fontSize = 19 
     }else if screenWidth>370{ 
      fontSize = 17 
     }else{ 
      fontSize = 15 

     } 
     let font = UIFont(name: "customfont", size: CGFloat(fontSize))