简体   繁体   中英

Change custom tableview cell's image

My situation : I make a custom cell named: BestQuestionListCell and I create a tableview in BestQuestionListViewController . In BestQuestionListCell I add a button on left. And I setImage on the button . Now when I tap the cell the image of the button does change. Now I want set one of these cell as selected when the view show up.

I tried to set image of button and I also tried to set the cell as selected. Either of them didn't work.

UISreenShot : The screenshot of BestQuestionListViewController

Here is the code of tableViewcell.

@implementation BestQuestionListCell
@synthesize questionLabel;
@synthesize authorLabel;
@synthesize ownerButton;
@synthesize starButton;

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    NSLog(@"I am selected! %@",selected?@"yes":@"no");
//    [super setSelected:selected animated:animated];
    if (selected) {
        [self.starButton setImage:[UIImage imageNamed:@"Fstar"] forState:UIControlStateNormal];
    }else{
        [self.starButton setImage:[UIImage imageNamed:@"Star"] forState:UIControlStateNormal];
    }
}

- (void)setButtonImage:(UIImage *)buttonImage{
    _buttonImage = buttonImage;
    [self.starButton setImage:[UIImage imageNamed:@"Fstar"] forState:UIControlStateNormal];
    [self setNeedsLayout];
    NSLog(@"nothing happened? %@",buttonImage);
}

And here is the tableview.

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *cellIdentifer = @"BestQuestionListCell";
    BestQuestionListCell *mainCell = (BestQuestionListCell *)[self.bestQuestionListTableView dequeueReusableCellWithIdentifier:cellIdentifer];

    if(mainCell == nil) {
        mainCell = [[[NSBundle mainBundle] loadNibNamed:cellIdentifer owner:self options:nil] firstObject];
    }

    if ( [DataSession sharedSession].subQuestionArray.count > 0) {
        mainCell.questionLabel.text = [[DataSession sharedSession].subQuestionArray[indexPath.row] question_content];
        mainCell.questionLabel.textColor = [UIColor colorWithRed:74/255.0f green:74/255.0f blue:74/255.0f alpha:1.0f];
        mainCell.questionLabel.backgroundColor = [UIColor whiteColor];
                mainCell.selectionStyle = UITableViewCellSelectionStyleNone;

    }
    return mainCell;
}

I didn't do anything in

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

I tried these three ways to solve this issue but didn't work.

[mainCell setButtonImage:[UIImage imageNamed:@"Fstar"]];
[mainCell.starButton setImage:[UIImage imageNamed:@"Fstar"] forState:UIControlStateNormal];
[mainCell setSelected:YES animated:YES];

As per your edited question below is the code work. I have done code commenting so that you can understand code properly, if still you have issue you can ask.

#import "BestQuestionListVC.h"
#import "BestQuestionListCell.h"

@interface BestQuestionListVC () <UITableViewDelegate, UITableViewDataSource>{
    NSArray *arrQuesList;
    NSArray *arrAuthorList;
    NSMutableArray *arrMutBtnSelected; // arrMut of bools, containing true/false of button as selected or not.

}

@property (strong, nonatomic) IBOutlet UITableView *tblBestQuestion;


@end

@implementation BestQuestionListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    // creating temp array of data
    arrQuesList     = @[@"ques #1", @"ques #2", @"ques #3", @"ques #4", @"ques #5", @"ques #6", @"ques #7", @"ques #8" ];
    arrAuthorList   = @[@"Author #1", @"Author #2", @"Author #3", @"Author #4", @"Author #5", @"Author #6", @"Author #7", @"Author #8" ];

    arrMutBtnSelected = [NSMutableArray new];  // alloc Mutable array

    // array of bools, initially all false as not any button is selected
    for (int i=0; i < arrQuesList.count; i++) {
        [arrMutBtnSelected addObject:[NSNumber numberWithBool:false]];
    }

    // for initially first button is selected.
    [arrMutBtnSelected replaceObjectAtIndex:0 withObject:[NSNumber numberWithBool:true]];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)btnStarClicked:(UIButton *)sender {
    // If one button is selected at one time
    // start
    /*
         [arrMutBtnSelected removeAllObjects];
         for (int i=0; i < arrQuesList.count; i++) {
         [arrMutBtnSelected addObject:[NSNumber numberWithBool:false]];
         }
         [arrMutBtnSelected replaceObjectAtIndex:sender.tag withObject:[NSNumber numberWithBool:true]];
    */
    // end

    // if user can selects multiple buttons
    // start
    /*
        if (sender.selected) {
            [arrMutBtnSelected replaceObjectAtIndex:sender.tag withObject:[NSNumber numberWithBool:false]];
        }
        else{
            [arrMutBtnSelected replaceObjectAtIndex:sender.tag withObject:[NSNumber numberWithBool:true]];
    }
    */
    // end

    [self.tblBestQuestion reloadData];
}


#pragma mark - TableViewDelegate

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewAutomaticDimension;
}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return arrQuesList.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BestQuestionListCell *quesCell = [tableView dequeueReusableCellWithIdentifier:@"BestQuestionListCell"];

    quesCell.lblQuestion.text   = arrQuesList[indexPath.row];
    quesCell.lblAuthor.text     = arrAuthorList[indexPath.row];
    quesCell.btnStar.tag = indexPath.row ;

    if (arrMutBtnSelected[indexPath.row] == [NSNumber numberWithBool:true]) {
        quesCell.btnStar.selected = true;
    }
    else{
        quesCell.btnStar.selected = false;
    }

    return quesCell;
}

@end

OUTPUT :

Initially when project runs :

在此处输入图片说明

Output for if user selects one button at a time :

在此处输入图片说明

Output for if user selects any multiple buttons

在此处输入图片说明

  //you could write only
 [mainCell setSelected:YES animated:YES];

It works for me.Please try it.

First set the IBOutLet in the tableViewCell.

Then in the viewController: at the cellForRowAtIndexPath method you can write this way:

UIImage *imageSelected = [UIImage imageNamed:@"your selected img name"];
UIImage *imageNotSelected = [UIImage imageNamed:@"your not selected img name"];
[cell.yourBtnName setImage:imageNotSelected forState:UIControlStateNormal];
[cell.yourBtnName setImage:imageSelected forState:UIControlStateSelected];

[cell.yourBtnName addTarget:self action:@selector(yourBtnClickMethod:) forControlEvents:UIControlEventTouchUpInside];

Then in action method:

-(void)yourBtnClickMethod:(UIButton *)btn{
    btn.selected = !btn.selected;
}

Hope it helps for you.Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM