2017-02-11 31 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

查看更新的答案,它適用於任何尺寸 –