Add button to UITableViewCell's Accessory View

前端 未结 10 1870
没有蜡笔的小新
没有蜡笔的小新 2021-01-01 16:41

Goal: when a user selects a cell, a button is added to that cell. Within my didSelectRowAtIndexPath function I have the following:

UIButton *downloadButton =         


        
相关标签:
10条回答
  • 2021-01-01 17:17

    Its always best to add any views that you are adding to a cell to cell.contentView. Also try to check if the accessoryView is nil.

    0 讨论(0)
  • 2021-01-01 17:18

    I had the same problem. Attempting to set the accessoryView to a UIButton which had an image caused it to not appear.

    The trick was to call [UIButton sizeToFit], to ensure its frame is set properly.

    0 讨论(0)
  • 2021-01-01 17:18

    Try This:

    [[self.tableView cellForRowAtIndexPath:indexPath].contentView addSubview:downloadButton];
    

    And remember to delete that button when the cell is being reused.

    0 讨论(0)
  • 2021-01-01 17:25

    Here is my example for a the full solution to your request:

    In my UITableViewCell subclass (I call it RNWNewItemCell):

    -(void)configureCell...
    {
       // create the button
       self.btnSeekDuplicate = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 22, 22)];
       // just make it yellow until we get our real image..
       self.btnSeekDuplicate.backgroundColor = [UIColor yellowColor];
       // add the handler for the button press
       [self.btnSeekDuplicate addTarget:self
                                 action:@selector(seekDuplicateButtonWasPressed) 
                       forControlEvents:UIControlEventTouchUpInside];
       // make it visible in the table cell...
       [self setAccessoryView:self.btnSeekDuplicate];
    }
    
    - (void)seekDuplicateButtonWasPressed
    {
        do something...
    }
    

    In my Table Code that uses the cell...

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
       ...
       RNWNewItemCell *aNewItemCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifierForNewItemCell forIndexPath:indexPath];
       [aNewItemCell configureCell...]
       ...
    }
    

    Note that accessoryButtonTappedForRowWithIndexPath is NOT called when you set the table cell's accessoryView. Probably because they assume you are using a view that responds to events.

    0 讨论(0)
  • 2021-01-01 17:27

    Swift

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
        let accessoryButton = UIButton.buttonWithType(UIButtonType.ContactAdd) as! UIButton
        cell.accessoryView = accessoryButton
    
        return cell
    }
    
    0 讨论(0)
  • 2021-01-01 17:27

    use this :

    cell.accessoryType=UITableViewCellAccessoryDetailDisclosureButton;
    
    0 讨论(0)
提交回复
热议问题