I have UITableView with custom UITableViewCell. Custom cell contains UIButton and UILabel.
Here I observe that UILabel text is change as I expected but UIButton text is not changing.
When I scroll out the button outside of the screen, change the label of UIButton.
Why it is not working? I have use Xcode 6 and use below code.
ViewController.h
#import <UIKit/UIKit.h>
#import "customTableViewCell.h"
@interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@end
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;
}
customeTableViewCell.h
#import <UIKit/UIKit.h>
@interface customTableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UIButton *button;
@property (weak, nonatomic) IBOutlet UILabel *label;
@end
This is because the UIButton class has multiple states (Normal, Selected, Highlighted, Disabled). When you change the text property of it's internal UILabel (textLabel property of UIButton), it's property is overriden by setState function, which is called when table is loaded.
To change text in the label of a button you need to call setTitle:forState: method. Here is your code fixed to work:
- (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;
}
For the sake of completion, you can also use setAttributedTitle:forState: method with NSAttributedString, so you can actually set your own specifically formatted string as a title.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With