2014-02-11 66 views
1

我是UIButton的子類設置應用程序的一些默認值,但我出於某種原因,我無法更改字體大小。UIButton的子類化和設置fontSize

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     // id button, set defaults 
     [self setTintColor:[UIColor blueColor]]; 
     [self.titleLabel setFont:[UIFont systemFontOfSize:40.0]]; 
     [self.layer setBorderWidth:1.0f]; 
     [self.layer setBorderColor:[[UIColor blackColor] CGColor]]; 
    } 
    return self; 
} 

我可以改變顏色和其他特性,但不是字體大小,它沒有效果?

idButton *LButton = [idButton buttonWithType:UIButtonTypeRoundedRect]; 
    [LButton setTitle:@"Login" forState:UIControlStateNormal]; 
    LButton.frame = CGRectMake(0, buttonY+(buttonHeight/2), screenWidth, buttonHeight); 
    [self addSubview:LButton]; 
+0

嘗試在更改屬性後調用'[self setNeedsDisplay]'。 – 68cherries

+0

你是否調用initWithFrame按鈕,或者它是否正在使用另一個init函數實例化,如故事板(initWithCoder) – Jbryson

+0

我正在使用mySubClass * Button = [mySubClass buttonWithType:UIButtonTypeRoundedRect];設置一個標題並將其添加爲另一個視圖中的子視圖 –

回答

2

的問題與您的代碼是的UIButton的方法setTitle:forState:將字體重置爲默認值。

解決方法之一是重寫此方法以使用NSAttributedString。這也將讓您設置其他屬性:

- (void) setTitle:(NSString *)customTitle forState:(UIControlState)state { 
    if (customTitle) { 
     NSMutableAttributedString *mas = [[NSMutableAttributedString alloc] initWithString:customTitle]; 
     NSRange range = NSMakeRange(0, [customTitle length]); 

     [mas addAttribute:NSFontAttributeName 
        value:[UIFont systemFontOfSize:40.0] 
        range:range]; 

     [mas addAttribute:NSKernAttributeName 
        value:@(1.1) 
        range:range]; 

     [self setAttributedTitle:mas forState:state]; 
    } else { 
     [super setTitle:customTitle forState:state]; 
    } 
} 
+0

這工作,謝謝一堆 –

0

哦,親愛的,我們是在一個泡菜...

你使用廈門國際銀行或情節串連圖板。

如果是這樣那麼initWithFrame:不會被調用

嘗試awakeFromNib

initWithCoder:

+0

它確實被調用,因爲其他屬性被添加!:)我添加了init :) –

+0

嘗試覆蓋setTitle:forState:一定要先打超級。更改此方法中的字體。 – AppHandwerker

0

+[UIButton buttonWithType]the documentation

buttonWithType:將不會返回UIButton子類的實例(例如您的LButton)。

由於你設置的initWithFrame方法的字體,你應該叫[[LButton alloc] initWithFrame:]代替:

idButton *LButton = [[LButton alloc] initWithFrame:frame]; 
0

我解釋如何做到這一點,inside this post.您正在尋找self.titleLabel.font.pointSize。您也可以使用UILabel擴展名執行此操作,但必須使用self.font.pointSize

如果您必須支持多種語言,則還可以在檢查語言代碼時添加其他方法,並根據此更改UIFont

你只需要設置UIFontawakeFromNib有:

[self.titleLabel setFont: 
    [UIFont fontWithName:kFont size:self.titleLabel.font.pointSize]]; 

,以獲得特定的字體。

- (UIFont *)whichFontShouldBeUsed{ 

    UIFont *fontToUse = [UIFont fontWithName:kFontBold 
             size:self.titleLabel.font.pointSize]; 

    if([_language isEqualToString:@"tr"] && 
     [_language isEqualToString:@"pl"]){ 

     fontToUse = [UIFont fontWithName:FOO 
            size:self.titleLabel.font.pointSize]; 
    } 
    return fontToUse; 
}