web-dev-qa-db-ja.com

属性としてIBに設定されたタイトルを持つUIButtonのタイトルをプログラムで変更します

UIButtonsのタイトルを使用する前に変更しました:

- (void)setTitle:(NSString *)title forState:(UIControlState)state

しかし 状況に遭遇しました 使用しているUIButtonには複数行のタイトルがあり、「プレーン」から「属性」に変更された場合にのみテキストを適切に中央揃えしますIBで。この方法でタイトルを変更すると、通常のsetTitle: forState:メソッドはボタンを更新しなくなりました。

UIButtonattributedタイトルをどのように変更しますか?

明確にするために、あなたは私が単に愚かな間違いをしているとは思わないので、デバッガを使用してUIButtonのプロパティを覗き、

- (NSString *)titleForState:(UIControlState)state

使用後

- (void)setTitle:(NSString *)title forState:(UIControlState)state

設定するには、設定した値を返します。問題は、IBでタイトルがattributedに設定されている限り、ボタンの外観を変更しないことです。私のコードは、これをplainに変更するだけで正常に機能します。しかし、これは上記のリンクで説明されているソリューションではありません。

20
Jeff Lockhart

帰属タイトルは以下を介して取得されます

- (NSAttributedString *)attributedTitleForState:(UIControlState)state

経由で設定

- (void)setAttributedTitle:(NSAttributedString *)title forState:(UIControlState)state

NSAttributedStringオブジェクトのフォーマットは少し複雑ですが、nilに設定するとタイトルがクリアされ、それが必要です。

58
Jeff Lockhart

View ControllerクラスでIBOutletとして指定されたボタンがあり、Interface Builderでアウトレットとして適切に接続されていますか(新しい参照アウトレットからファイル所有者へのCtrlドラッグとUIButtonオブジェクトの選択)?通常、これらの症状が見られるとき、私が抱えている問題です。最初に指定してください-@property(non atomic,strong)IBOutlet UIButton *mybutton;

それから

[myButton setTitle: @"myTitle" forState: UIControlStateNormal];

9
Christien

ここにある

_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を変更する必要はありません

4
Christien

Swift-ボタンタイトルの赤い取り消し線フォントの場合:

let attributedStringForInvalid = NSAttributedString(string: "I'm Invalid!", attributes: [
  NSStrikethroughStyleAttributeName: true,
  NSForegroundColorAttributeName: UIColor.redColor()
  ])
myButton.setAttributedTitle(attributedStringForInvalid, forState: UIControlState.Normal)
1
ObjectiveTC

属性付きフォントを表示するには、次の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];
1
iCyberPaul