2015-10-22 31 views
0

我正在繼承UILabelUITextField,以便在3.5英寸設備上更改字體大小(因爲這不能使用大小類別獨立於4和4.7英寸設備)。替代3.5英寸iOS設備的字體大小

如果在layoutSubviews()中完成字體更改,但會重複調用字體,以便字體大小最終爲零。我試圖找到另一個地方來設置它只能調用一次,仍然可以覆蓋字體大小。

代碼:

if (UIDevice.currentDevice().orientation == .Portrait) { 
    if (UIScreen.mainScreen().bounds.size.height < 568) { 
     self.font = UIFont(name: "Score Board", size: (self.font.pointSize - CGFloat(10.0))) 
    } else { 
     self.font = UIFont(name: "Score Board", size: self.font.pointSize) 
    } 
} else { 
    if (UIScreen.mainScreen().bounds.size.width < 568) { 
     self.font = UIFont(name: "Score Board", size: (self.font.pointSize - CGFloat(10.0))) 
    } else { 
     self.font = UIFont(name: "Score Board", size: self.font.pointSize) 
    } 
} 

我也嘗試過在didMoveToSuperview()willMovetoSuperview(),它只是調用一次,但它實際上並沒有改變字體。我也嘗試過init,但是字體沒有設置。

import Foundation 
import UIKit 

class CustomUILabel : UILabel { 

    override func didMoveToSuperview() { 
     super.didMoveToSuperview() 
     // Code from above 
    } 
} 
+0

的問題是,你有這樣的代碼放在一個被調用一遍又一遍的方法,這樣的事情應該只存在於視圖負荷,做方向改變方法 – Knight0fDragon

+0

@ Knight0fDragon我不認爲有一個viewDidLoad,它是'UITextField'和'UILabel'的子類...有沒有你知道的任何函數只有在我可以這樣做時才被調用? –

+0

是的,你嘗試覆蓋初始化?,也可以使用willMoveToSuperview(newSuperview:UIView?) – Knight0fDragon

回答

1

font屬性重寫didSet

class MyLabel : UILabel { 

    private func shouldShrinkFont() -> Bool { 
     let size = UIScreen.mainScreen().bounds.size 
     // This check works regardless of orientation. 
     return size.width + size.height == 480 + 320 
    } 

    override var font: UIFont! { 
     didSet { 
      if shouldShrinkFont() { 
       super.font = UIFont(name: "Score Board", size: font.pointSize - 10) 
      } 
     } 
    } 

} 
+0

我可以做同樣的UITextField子類嗎?我將兩者都進行了分類...我不明白爲什麼蘋果不能爲我們提供3級的尺寸。5英寸設備..... –

+0

試試看看。 –

+0

我收到一個錯誤 - :'線程1:EXC_BAD_ACCESS'在我的UILabel子類 –

相關問題