Кнопка «Добавить» в представление аксессуаров UITableViewCell - PullRequest
16 голосов
/ 12 сентября 2011

Цель: когда пользователь выбирает ячейку, в эту ячейку добавляется кнопка.В моей функции didSelectRowAtIndexPath у меня есть следующее:

UIButton *downloadButton = [[UIButton alloc] init];
downloadButton.titleLabel.text = @"Download";
[downloadButton setFrame:CGRectMake(40, 0, 100, 20)];
[[self.tableView cellForRowAtIndexPath:indexPath].accessoryView addSubview:downloadButton];
[[self.tableView cellForRowAtIndexPath:indexPath].accessoryView setNeedsLayout];

[downloadButton release];

К сожалению, это, похоже, ничего не делает.Я перерисовываю коррекцию клетки?Нужно ли добавить его по-другому?

Ответы [ 10 ]

23 голосов
/ 12 сентября 2011

Попробуйте этот блок кода вместо блока, который вы указали выше:

UIButton *downloadButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[downloadButton setTitle:@"Download" forState:UIControlStateNormal];
[downloadButton setFrame:CGRectMake(0, 0, 100, 35)];
[tableView cellForRowAtIndexPath:indexPath].accessoryView = downloadButton;

Это должно отобразить кнопку, но вам все равно нужно будет подключить к ней какой-то селектор, используя addTarget.(Я не уверен, что прослушивание делегата accessoryButtonTappedForRowWithIndexPath будет работать в этом случае, попробуйте сначала и посмотрите, срабатывает ли оно при нажатии вашей кнопки.)

8 голосов
/ 04 ноября 2014

У меня была такая же проблема. Попытка установить accessoryView для UIButton, у которого было изображение, заставляла его не появляться.

Трюк состоял в том, чтобы вызвать [UIButton sizeToFit], чтобы убедиться, что его кадр установлен правильно.

7 голосов
/ 12 сентября 2011

Назначьте кнопку как вспомогательный вид, а не как подвид вспомогательного вида.

UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryView = downloadButton;
1 голос
/ 15 марта 2019

Swift 4 и выше: Добавить кнопку в представление аксессуаров UITableViewCell

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = Table.dequeueReusableCell(withIdentifier: "identifier", for: indexPath)

            let accessoryButton = UIButton(type: .custom)
            accessoryButton.addTarget(self, action: #selector(deleteCell(sender:)), for: .touchUpInside)
            accessoryButton.setImage("Add_image", for: .normal) 
            accessoryButton.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
            accessoryButton.contentMode = .scaleAspectFit

            cell.accessoryView = accessoryButton as UIView

            return cell
    }

Добавить метод выбора

    func deleteCell(sender: AnyObject)
    {
        let pointInTable: CGPoint = sender.convert(sender.bounds.origin, to: self.Table)
        let cellIndexPath = self.Table.indexPathForRow(at: pointInTable)
        let point = cellIndexPath!.row

    }
1 голос
/ 03 ноября 2016
let button = UIButton(type:.roundedRect)
button.setTitle("A", for: .normal)
button.sizeToFit()
cell.accessoryView = button
1 голос
/ 20 февраля 2014

Вот мой пример полного решения вашего запроса:

В моем подклассе UITableViewCell (я называю это 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...
}

В моем коде таблицы, который использует ячейку...

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

Обратите внимание, что accessoryButtonTappedForRowWithIndexPath НЕ вызывается при установке accessoryView ячейки таблицы.Возможно, потому что они предполагают, что вы используете представление, которое реагирует на события.

1 голос
/ 12 сентября 2011

Попробуйте:

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

И не забудьте удалить эту кнопку при повторном использовании ячейки.

0 голосов
/ 29 сентября 2015

используйте это:

cell.accessoryType=UITableViewCellAccessoryDetailDisclosureButton;
0 голосов
/ 25 августа 2015

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 голосов
/ 12 сентября 2011

Всегда лучше добавить любые виды, которые вы добавляете в ячейку, к cell.contentView.Также попробуйте проверить, равен ли accessoryView нулю.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...