在从XIB加载的自定义视图中修改UIButton的标题标签

时间:2014-08-12 13:00:09

标签: ios objective-c uibutton uilabel

在我的iOS项目中,我加载了一个来自XIB文件的自定义视图,如Paul Solt在他的CustomView(或CompositeXIB)教程中所描述的那样。

_customView = [[[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil] firstObject];
[self addSubview:_customView];

在自定义视图中,我需要根据应用状态自定义按钮标题。所以我添加了一个IBOutlet UIButton属性来修改按钮的标题标签。

在头文件中:@property (weak, nonatomic) IBOutlet UIButton *theButton;(此属性链接到XIB文件中的相应UIButton)

在实现文件的init方法中:_theButton.titleLabel.text = @"My own title";

在init方法按预期覆盖XIB文件中定义的那个之后,按钮的标题设置得很好,但点击该按钮会导致重置XIB中定义的标题。 如果标题未在XIB中定义,那么按钮的标题将始终为空。

2 个答案:

答案 0 :(得分:1)

设置“Normal”以及“Selected”状态的标题。

[YourButton setTitle:@"titleNormal" forState:UIControlStateNormal];
[YourButton setTitle:@"titleSelected" forState:UIControlStateSelected];

答案 1 :(得分:0)

请使用desitit for UIControlState

  [buttonVariable setTitle:@"Your Title" forState:UIControlState)];

UIControlState是

typedef NS_OPTIONS(NSUInteger, UIControlState) {
  UIControlStateNormal       = 0,
  UIControlStateHighlighted  = 1 << 0,                  // used when UIControl isHighlighted is set
  UIControlStateDisabled     = 1 << 1,
  UIControlStateSelected     = 1 << 2,                  // flag usable by app (see below)
  UIControlStateApplication  = 0x00FF0000,              // additional flags available for application use
  UIControlStateReserved     = 0xFF000000               // flags reserved for internal framework use
};