2017-02-11 28 views
1

我有方形的按钮,其大小可能会有所不同,无论它显示在iPad或iPhone上。 我想按钮标题的字体调整到按钮的大小,即。所以它们在更大的iPad屏幕上看起来不会太小,或者在更小的iPhone屏幕上看起来太大。查找UIButton调整后的字体大小值?

我想出了以下解决方案:

// Buttons is an outlet collection 
for button in Buttons { 
      button.titleLabel?.adjustsFontSizeToFitWidth = true 
      button.titleEdgeInsets = UIEdgeInsetsMake(button.frame.height/3, button.frame.width/3, button.frame.height/3, button.frame.width/3) 
      button.titleLabel!.numberOfLines = 1 
      button.titleLabel!.minimumScaleFactor = 0.1 
      button.clipsToBounds = true 
      button.titleLabel?.baselineAdjustment = UIBaselineAdjustment.alignCenters 

      print(button.titleLabel!.font.pointSize) 


     } 

这提供了基于标题的宽度字体的大小的调节。因此,与标题较长的按钮相比,标题较短的按钮将具有更大的字体。

我想为所有按钮使用相同的字体大小,所以我想访问其中一个按钮的调整大小(比方说最小)以将其设置为所有按钮。我怎么能这样做?

另外我想将字体调整到按钮高度,而不是宽度,但无法找到工作的解决方案。

+0

请检查答案并回复 –

+0

查看已更新的答案,现在可用于任何值 –

+0

我在iOS开发过程中很早就遇到了这个问题,但我现在意识到这不是一种好的设计方法应用程序。之所以做这件事不容易,是因为真正的内容不应该在更大的屏幕上“增长”,而是改变应用程序以显示更多内容。只是一个想法,但我发现它是一个更好的开发应用程序的方式。 –

回答

0

这是将所有按钮的字体大小设置为最小大小的解决方案(其中包括)。

步骤1.我已经初始化了一些新的按钮,用于测试:

let button = UIButton() 
button.titleLabel!.font = UIFont(name: "Helvetica", size: 20) 
let button2 = UIButton() 
button2.titleLabel!.font = UIFont(name: "Helvetica", size: 16) 
let button3 = UIButton() 
button3.titleLabel!.font = UIFont(name: "Helvetica", size: 19) 
let Buttons = [button, button2, button3] 

步骤2.然后,我已经添加了一个可变称为min,我已经与大的值大于初始化它几乎任何可能的按钮字体大小,100,像这样:

var min = CGFloat(Int.max) 

第3步:在那之后,我增加了一些更多的代码到你的循环:

for btn in Buttons{ 
    // here goes your code for your buttons(the code from the question) 
    // then my code: 
    if (btn.titleLabel?.font.pointSize)! < min{ 
     min = (btn.titleLabel?.font.pointSize)! // to get the minimum font size of any of the buttons 
    } 
} 

print(min) // prints 16, which is correct amongst the value [20,19,16] 

使你的代码看起来就像这样:

for btn in Buttons{ 
    btn.titleLabel?.adjustsFontSizeToFitWidth = true 
    btn.titleEdgeInsets = UIEdgeInsetsMake(btn.frame.height/3, btn.frame.width/3, btn.frame.height/3, btn.frame.width/3) 
    btn.titleLabel!.numberOfLines = 1 
    btn.titleLabel!.minimumScaleFactor = 0.1 
    btn.clipsToBounds = true 
    btn.titleLabel?.baselineAdjustment = UIBaselineAdjustment.alignCenters 
    print(btn.titleLabel!.font.pointSize) 
    if (btn.titleLabel?.font.pointSize)! < min{ 
      min = (btn.titleLabel?.font.pointSize)! // to get the minimum font size of any of the buttons 
    }  
} 

第4步:所有按钮的字体大小设置为min

Buttons.map { $0.titleLabel?.font = UIFont(name:($0.titleLabel?.font.fontName)! , size: min) } 

for btn in Buttons{ 
    btn.titleLabel?.font = UIFont(name: (btn.titleLabel?.font.fontName)!, size: min) 
} 

如果您的最小字体大小,让我们说...... ,那么所有的按键的字体大小将成为。


就是这样。希望能帮助到你!

+0

不幸的是,我不知道按钮的字体大小。假设我给所有按钮设置了100的字体大小,然后使用'adjustsFontSizeToFitWidth'缩小显示。 'button.titleLabel!.font.pointSize'仍然会返回100,即使字体已经缩小。 – Fredovsky

+0

然后将其设置为var min = CGFloat(Int.max) –

+0

查看更新的答案,它适用于任何尺寸 –