20

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

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

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

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

明確にするために、私が愚かな間違いを犯しているとは思わないように、デバッガーを使用してのプロパティを確認し、UIButtonの出力をログに記録しました

- (NSString *)titleForState:(UIControlState)state

使用後

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

設定すると、設定した値が返されます。問題は、タイトルがIBで属性に設定されている限り、ボタンの外観が変更されないことです。私のコードは、これをプレーンに変更するだけで正常に機能します。しかし、これは上記のリンクで説明されているような解決策ではありません。

4

5 に答える 5

59

属性付きのタイトルは次の方法で取得されます

- (NSAttributedString *)attributedTitleForState:(UIControlState)state

経由で設定

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

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

于 2012-10-02T01:04:57.273 に答える
9

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

それから

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

于 2012-09-29T11:55:42.477 に答える
4

これが1つです

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

于 2012-09-29T11:16:11.027 に答える
1

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

let attributedStringForInvalid = NSAttributedString(string: "I'm Invalid!", attributes: [
  NSStrikethroughStyleAttributeName: true,
  NSForegroundColorAttributeName: UIColor.redColor()
  ])
myButton.setAttributedTitle(attributedStringForInvalid, forState: UIControlState.Normal)
于 2015-08-17T22:31:43.523 に答える
1

属性付きフォントを表示するには、次の 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];
于 2015-12-07T13:14:59.320 に答える