[英]Programmatically change title of UIButton whose title was set in IB as attributed
我在使用之前更改了UIButton
的標題:
- (void)setTitle:(NSString *)title forState:(UIControlState)state
但我遇到的情況是我正在使用的UIButton
有一個多行標題,只有在IB中從“普通”變為“歸屬”時才會正確居中。 當以這種方式更改標題時,通常的setTitle: forState:
方法不再更新按鈕。
如何更改UIButton
的屬性標題?
為了澄清,所以你不要假設我只是犯了一個愚蠢的錯誤,我已經使用調試器來查看UIButton
的屬性並記錄輸出
- (NSString *)titleForState:(UIControlState)state
使用后
- (void)setTitle:(NSString *)title forState:(UIControlState)state
設置它返回剛剛設置的值。 問題是只要標題設置為IB中的屬性 ,它就不會改變按鈕的外觀。 只需將其更改為plain,我的代碼就可以正常工作。 但這不是上面鏈接中描述的解決方案。
歸屬標題是通過
- (NSAttributedString *)attributedTitleForState:(UIControlState)state
並設置通過
- (void)setAttributedTitle:(NSAttributedString *)title forState:(UIControlState)state
格式化NSAttributedString
對象有點復雜,但將其設置為nil
將清除標題,這就是我所需要的。
您是否在視圖控制器類中將按鈕指定為IBOutlet,並且它是否正確連接為Interface Builder中的插座(從新引用插座拖動到文件所有者並選擇您的UIButton對象)? 當我看到這些症狀時,這通常是我遇到的問題。首先指定 - @property @property(non atomic,strong)IBOutlet UIButton *mybutton;
然后
[myButton setTitle: @"myTitle" forState: UIControlStateNormal];
這是一個
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:@selector(aMethod:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Title" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];
無需在- (void)setTitle:(NSString *)title
進行更改
Swift - 對於按鈕標題中的紅色刪除線字體:
let attributedStringForInvalid = NSAttributedString(string: "I'm Invalid!", attributes: [
NSStrikethroughStyleAttributeName: true,
NSForegroundColorAttributeName: UIColor.redColor()
])
myButton.setAttributedTitle(attributedStringForInvalid, forState: UIControlState.Normal)
我必須使用以下4行來顯示屬性字體。 在IB中,標題設置為簡單而不歸因。
// Get the library font
UIFont *termsFont = [MTHGAppearanceController defaultFontOfSize:[MTHGAppearanceController defaultButtonFontSizeForDevice]];
// Set the font attributes required, using our librarby function for setting the colour
NSDictionary *fontAttributes = @{NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle),NSBackgroundColorAttributeName: [UIColor clearColor], NSFontAttributeName: termsFont, NSForegroundColorAttributeName:[UIColor mthg_color255WithRed:128.0f green:128.0f blue:128.0f alpha:1.0f]};
// Configure the text we want displayed using the font set above
NSAttributedString *termsString = [[NSAttributedString alloc]initWithString:@"Terms" attributes:fontAttributes];
// Now finally display the text in the required font
[self.termsButtonOutlet setAttributedTitle:termsString forState:UIControlStateNormal];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.