Использование пользовательского изображения для accessoryView UITableViewCell и предоставление ему ответа на UITableViewDelegate - PullRequest
138 голосов
/ 15 мая 2009

Я использую пользовательский нарисованный UITableViewCell, в том числе и для ячейки accessoryView. Моя настройка для accessoryView происходит примерно так:

UIImage *accessoryImage = [UIImage imageNamed:@"accessoryDisclosure.png"];
UIImageView *accImageView = [[UIImageView alloc] initWithImage:accessoryImage];
accImageView.userInteractionEnabled = YES;
[accImageView setFrame:CGRectMake(0, 0, 28.0, 28.0)];
self.accessoryView = accImageView;
[accImageView release];

Также при инициализации ячейки, используя initWithFrame:reuseIdentifier:, я установил следующее свойство:

self.userInteractionEnabled = YES;

К сожалению, в моем UITableViewDelegate мой метод tableView:accessoryButtonTappedForRowWithIndexPath: (попробуйте повторить это 10 раз) не запускается. Делегат определенно подключен правильно.

Что может быть упущено?

Спасибо всем.

Ответы [ 10 ]

228 голосов
/ 15 мая 2009

К сожалению, этот метод не вызывается, пока не будет нажат внутренний тип кнопки, предоставленный при использовании одного из предопределенных типов. Чтобы использовать свой собственный, вам нужно будет создать аксессуар в виде кнопки или другого подкласса UIControl (я бы порекомендовал кнопку, используя -buttonWithType:UIButtonTypeCustom и настройку изображения кнопки, а не UIImageView).

Вот некоторые вещи, которые я использую в Outpost, который настраивает достаточно стандартных виджетов (чуть-чуть, чтобы они соответствовали нашей окраске бирюзового цвета), которые я создал, создав собственный промежуточный подкласс UITableViewController, чтобы содержать код утилиты для всех других табличных представлений ( теперь они подкласс OPTableViewController).

Во-первых, эта функция возвращает новую кнопку раскрытия подробностей, используя нашу пользовательскую графику:

- (UIButton *) makeDetailDisclosureButton
{
    UIButton * button = [UIButton outpostDetailDisclosureButton];

[button addTarget: self
               action: @selector(accessoryButtonTapped:withEvent:)
     forControlEvents: UIControlEventTouchUpInside];

    return ( button );
}

Кнопка вызовет эту подпрограмму, когда она будет завершена, которая затем передает стандартную подпрограмму UITableViewDelegate для дополнительных кнопок:

- (void) accessoryButtonTapped: (UIControl *) button withEvent: (UIEvent *) event
{
    NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint: [[[event touchesForView: button] anyObject] locationInView: self.tableView]];
    if ( indexPath == nil )
        return;

    [self.tableView.delegate tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
}

Эта функция находит строку, получая местоположение в табличном представлении касания из события, предоставленного кнопкой, и запрашивая в табличном представлении путь индекса строки в этой точке.

77 голосов
/ 07 октября 2010

Я нашел этот сайт очень полезным: пользовательский вид аксессуаров для вашего телефона в iphone

Короче говоря, используйте это в cellForRowAtIndexPath::

UIImage *image = (checked) ? [UIImage imageNamed:@"checked.png"] : [UIImage imageNamed:@"unchecked.png"];

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
button.frame = frame;
[button setBackgroundImage:image forState:UIControlStateNormal];

[button addTarget:self action:@selector(checkButtonTapped:event:)  forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor = [UIColor clearColor];
cell.accessoryView = button;

затем реализуйте этот метод:

- (void)checkButtonTapped:(id)sender event:(id)event
{
    NSSet *touches = [event allTouches];
    UITouch *touch = [touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];

    if (indexPath != nil)
    {
        [self tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
    }
}
7 голосов
/ 04 мая 2012

Мой подход заключается в создании подкласса UITableViewCell и инкапсуляции логики, которая будет вызывать в нем обычный метод UITableViewDelegate.

// CustomTableViewCell.h
@interface CustomTableViewCell : UITableViewCell

- (id)initForIdentifier:(NSString *)reuseIdentifier;

@end

// CustomTableViewCell.m
@implementation CustomTableViewCell

- (id)initForIdentifier:(NSString *)reuseIdentifier;
{
    // the subclass specifies style itself
    self = [super initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuseIdentifier];
    if (self) {
        // get the button elsewhere
        UIButton *accBtn = [ViewFactory createTableViewCellDisclosureButton];
        [accBtn addTarget: self
                   action: @selector(accessoryButtonTapped:withEvent:)
         forControlEvents: UIControlEventTouchUpInside];
        self.accessoryView = accBtn;
    }
    return self;
}

#pragma mark - private

- (void)accessoryButtonTapped:(UIControl *)button withEvent:(UIEvent *)event
{
    UITableViewCell *cell = (UITableViewCell*)button.superview;
    UITableView *tableView = (UITableView*)cell.superview;
    NSIndexPath *indexPath = [tableView indexPathForCell:cell];
    [tableView.delegate tableView:tableView accessoryButtonTappedForRowWithIndexPath:indexPath];
}

@end
3 голосов
/ 02 мая 2013

Расширение ответа Джима Дави выше:

Будьте осторожны, когда используете UISearchBarController с UITableView. В этом случае вы хотите проверить self.searchDisplayController.active и использовать self.searchDisplayController.searchResultsTableView вместо self.tableView. В противном случае вы получите неожиданные результаты, когда searchDisplayController активен, особенно когда прокручиваются результаты поиска.

Например:

- (void) accessoryButtonTapped:(UIControl *)button withEvent:(UIEvent *)event
{
    UITableView* tableView = self.tableView;
    if(self.searchDisplayController.active)
        tableView = self.searchDisplayController.searchResultsTableView;

    NSIndexPath * indexPath = [tableView indexPathForRowAtPoint:[[[event touchesForView:button] anyObject] locationInView:tableView]];
    if(indexPath)
       [tableView.delegate tableView:tableView accessoryButtonTappedForRowWithIndexPath:indexPath];
}
2 голосов
/ 22 февраля 2013

При нажатии кнопки ее можно вызвать следующим методом внутри подкласса UITableViewCell

 -(void)buttonTapped{
     // perform an UI updates for cell

     // grab the table view and notify it using the delegate
     UITableView *tableView = (UITableView *)self.superview;
     [tableView.delegate tableView:tableView accessoryButtonTappedForRowWithIndexPath:[tableView indexPathForCell:self]];

 }
2 голосов
/ 11 июля 2012
  1. Определение макроса для тегов кнопок:

    #define AccessoryViewTagSinceValue 100000 // (AccessoryViewTagSinceValue * sections + rows) must be LE NSIntegerMax
    
  2. Создать кнопку и установить cell.accessoryView при создании ячейки

    UIButton *accessoryButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
    accessoryButton.frame = CGRectMake(0, 0, 30, 30);
    [accessoryButton addTarget:self action:@selector(accessoryButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    cell.accessoryView = accessoryButton;
    
  3. Установить cell.accessoryView.tag по indexPath в методе UITableViewDataSource -tableView: cellForRowAtIndexPath:

    cell.accessoryView.tag = indexPath.section * AccessoryViewTagSinceValue + indexPath.row;
    
  4. Обработчик событий для кнопок

    - (void) accessoryButtonTapped:(UIButton *)button {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:button.tag % AccessoryViewTagSinceValue
                                                    inSection:button.tag / AccessoryViewTagSinceValue];
    
        [self.tableView.delegate tableView:self.tableView accessoryButtonTappedForRowWithIndexPath:indexPath];
    }
    
  5. Реализация метода UITableViewDelegate

    - (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
        // do sth.
    }
    
1 голос
/ 02 июля 2012

При подходе Янченко я должен был добавить: [accBtn setFrame:CGRectMake(0, 0, 20, 20)];

Если вы используете файл xib для настройки вашего tableCell, тогда initWithStyle: reuseIdentifier: не будет вызван.

Вместо переопределения:

-(void)awakeFromNib
{
//Put your code here 

[super awakeFromNib];

}
1 голос
/ 06 октября 2010

Вы должны использовать UIControl для правильного получения отправки события (например, UIButton) вместо простого UIView/UIImageView.

0 голосов
/ 05 июня 2019

Swift 5

Этот подход использует UIButton.tag для хранения indexPath с использованием основного сдвига битов. Этот подход будет работать в 32- и 64-разрядных системах, если у вас не более 65535 разделов или строк.

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cellId")
    let accessoryButton = UIButton(type: .custom)
    accessoryButton.setImage(UIImage(named: "imageName"), for: .normal)
    accessoryButton.sizeToFit()
    accessoryButton.addTarget(self, action: #selector(handleAccessoryButton(sender:)), for: .touchUpInside)

    let tag = (indexPath.section << 16) | indexPath.row
    accessoryButton.tag = tag
    cell?.accessoryView = accessoryButton

}

@objc func handleAccessoryButton(sender: UIButton) {
    let section = sender.tag >> 16
    let row = sender.tag & 0xFFFF
    // Do Stuff
}
0 голосов
/ 03 ноября 2014

Начиная с iOS 3.2, вы можете избежать кнопок, которые рекомендуют другие, и вместо этого использовать ваш UIImageView с распознавателем жестов касания. Обязательно включите взаимодействие с пользователем, которое по умолчанию отключено в UIImageViews.

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