简体   繁体   中英

UITableViewCell button to expand text in a cell - how to do this?

I've got a UITableView with a list of 10 sections, each containing a textLabel .

I've limited the amount of text in each cell to 10 lines and put a button to allow to user to expand the text in the cell.

The problem is, I want to change the text on the button when it's clicked between "show more" (if cell is not expanded) and "show less" (if cell is expanded). How can I do that?

Right now I have this code in cellForRowAtIndexPath . It doesnt seem to work correct, sometimes the button displays "show less" when there are only 10 lines displayed.

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ButtonCell"];

if (!cell) {

  UIButton *readmoreButton = [UIButton buttonWithType:UIButtonTypeCustom];

    [readmoreButton setTitle:@"Read More" forState:UIControlStateNormal];
  [cell addSubview:readmoreButton];

}
else {

  NSEnumerator *e = [cell.subviews objectEnumerator];
  id object;
  while (object = [e nextObject]) {
    if ([object class]==UIButton.class && [((UIButton*)object).titleLabel.text isEqualToString:@"Read Less"])
      ((UIButton*)object).titleLabel.text = @"Read More";
    }
}

The following method is called when the user clicks the button. The NSMutableArray ProposalInfo keeps track of which cell is/is not expanded.

- (void)toggleFullProposal:(id) sender {

// get cell
NSIndexPath *index = [self.tableView indexPathForCell:(UITableViewCell *)[sender superview]];

ProposalInfo *proposalInfo = [self.proposalInfoArray objectAtIndex:index.section];

if ([proposalInfo expanded]==YES) {

    [proposalInfo setExpanded:NO];

    [(UIButton *)sender setTitle:@"Read More" forState:UIControlStateNormal];

}  else {

    [proposalInfo setExpanded:YES];

    [(UIButton *)sender setTitle:@"Read Less" forState:UIControlStateNormal];

}

// create index paths to reload
NSMutableArray *indexPathsToReload = [[NSMutableArray alloc] init];
[indexPathsToReload addObject:[NSIndexPath indexPathForRow:0 inSection:index.section]];

// refresh
[self.tableView reloadRowsAtIndexPaths:indexPathsToReload withRowAnimation:UITableViewRowAnimationNone];

}

When the button is clicked make sure that now you set the full text to the cell. And then only reload the cell and mind it you need to fix the height of label in layoutSubviews: and then return appropriate height for heightForRowAtIndexPath: as well.

((MyCell*)[tableview cellForRowAtIndexPath:buttonClickedindexPath]).fullText = myModel.fullText;

and in the layoutSubviews : method of the custom class cell expand the frame of the the label so as to fit the text inside, then return the appropriate height in heightForRowAtIndexPath: and that should do the trick.

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