Использование настраиваемого изображения для аксессуара UITableViewCell и его ответ на UITableViewDelegate
Я использую настраиваемый UITableViewCell, в том числе для ячейки 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 раз) не запускается. Делегат определенно подключен должным образом.
Что может быть возможно отсутствовать?
Спасибо всем.
Ответы
Ответ 1
К сожалению, этот метод не вызывается, если не используется внутренний тип кнопки, предоставляемый при использовании одного из предопределенных типов. Чтобы использовать свои собственные, вам нужно будет создать свой аксессуар в качестве кнопки или другого подкласса 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];
}
Эта функция находит строку, получая местоположение в виде таблицы касания от события, предоставленного кнопкой, и запрашивая представление таблицы для пути индекса строки в этой точке.
Ответ 2
Я нашел этот сайт очень полезным:
пользовательский аксессуар для вашего uitableview в 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];
}
}
Ответ 3
Мой подход заключается в создании подкласса 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
Ответ 4
Расширение Джима Дови ответить выше:
Будьте осторожны, когда вы используете 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];
}
Ответ 5
-
Определите макрос для тегов кнопок:
#define AccessoryViewTagSinceValue 100000 // (AccessoryViewTagSinceValue * sections + rows) must be LE NSIntegerMax
-
Создайте кнопку и установите 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;
-
Установить cell.accessoryView.tag с помощью indexPath в UITableViewDataSource method -tableView: cellForRowAtIndexPath:
cell.accessoryView.tag = indexPath.section * AccessoryViewTagSinceValue + indexPath.row;
-
Обработчик событий для кнопок
- (void) accessoryButtonTapped:(UIButton *)button {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:button.tag % AccessoryViewTagSinceValue
inSection:button.tag / AccessoryViewTagSinceValue];
[self.tableView.delegate tableView:self.tableView accessoryButtonTappedForRowWithIndexPath:indexPath];
}
-
Внедрить метод UITableViewDelegate
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
// do sth.
}
Ответ 6
Когда кнопка нажата, вы можете вызвать ее следующим образом в подклассе 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]];
}
Ответ 7
Вы должны использовать UIControl
для правильной отправки события (например, UIButton
) вместо простого UIView/UIImageView
.
Ответ 8
С приближением Янченко мне пришлось добавить: [accBtn setFrame:CGRectMake(0, 0, 20, 20)];
Если вы используете xib файл для настройки tableCell, тогда initWithStyle: reuseIdentifier: wont get called.
Вместо этого переопределить:
-(void)awakeFromNib
{
//Put your code here
[super awakeFromNib];
}
Ответ 9
Как и в iOS 3.2, вы можете избежать кнопок, которые другие здесь рекомендуют, и вместо этого использовать ваш UIImageView с помощью распознавателя жестов. Обязательно включите взаимодействие с пользователем, которое по умолчанию отключено в UIImageViews.
Ответ 10
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
}