在UITableViewCell中放置UIButton时,TitleLabel被破坏了

izu*_*chy 2 objective-c uibutton uitableview ios

我有UITableView自定义UITableViewCell.自定义单元格包含UIButtonUILabel.

在这里,我观察到UILabel文本正如我预期的UIButton那样发生变化但文本没有变化.

当我滚出屏幕外的按钮时,更改UIButton的标签.

为什么不工作?我使用Xcode 6并使用下面的代码.


ViewController.h

#import <UIKit/UIKit.h>
#import "customTableViewCell.h"

@interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end
Run Code Online (Sandbox Code Playgroud)

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"customTableViewCell" bundle:nil] forCellReuseIdentifier:@"customTableViewCell"];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    customTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"customTableViewCell" forIndexPath:indexPath];
    cell.button.titleLabel.text = @"Label does not change immediately";
    cell.label.text = @"change label";
    return cell;
}
Run Code Online (Sandbox Code Playgroud)

customeTableViewCell.h

#import <UIKit/UIKit.h>

@interface customTableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UIButton *button;
@property (weak, nonatomic) IBOutlet UILabel *label;

@end
Run Code Online (Sandbox Code Playgroud)

Leg*_*ess 11

这是因为UIButton该类具有多个状态(Normal,Selected,Highlighted,Disabled).当你更改它的内部UILabel(textLabel属性UIButton)的text属性时,它的属性被setState函数覆盖,当加载表时调用它.

要更改按钮标签中的文本,您需要调用setTitle:forState:方法.这是你的代码修复工作:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    customTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"customTableViewCell" forIndexPath:indexPath];
    [cell.button setTitle:@"Now it works" forState:UIControlStateNormal];
    cell.label.text = @"change label";
    return cell;
}
Run Code Online (Sandbox Code Playgroud)

为了完成,您还可以使用setAttributedTitle:forState:方法NSAttributedString,因此您实际上可以将自己的特定格式的字符串设置为标题.