[英]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.