Подтвердить что ты не робот

IOS 7 - Как получить индексную кнопку от кнопки, расположенной в UITableViewCell

Я программно создал UITableView и добавил UISwitch в это представление сотового аксессуара.

Это мой код для UISwitch в представлении аксессуаров ячейки в cellForRowAtIndexPath.

UISwitch *accessorySwitch = [[UISwitch alloc]initWithFrame:CGRectZero];
[accessorySwitch setOn:NO animated:YES];
[accessorySwitch addTarget:self action:@selector(changeSwitch:) forControlEvents:UIControlEventValueChanged];
cell.accessoryView = accessorySwitch;

Это метод, который вызывается после нажатия кнопки.

- (void)changeSwitch:(UISwitch *)sender{

    UITableViewCell *cell = (UITableViewCell *)[sender superview];

    NSIndexPath *indexPath = [self.filterTableView indexPathForCell:cell];
    NSLog(@"%ld",(long)indexPath);

 ……………. My other code…….
}

Я могу напечатать значение пути индекса в iOS 6 Но в iOS 7 он печатает нуль,

Мне что-то не хватает в iOS 7 или есть какой-то другой подход, чтобы получить indexPath в iOS 7

Спасибо, Арун.

4b9b3361

Ответ 1

NSLog(@"%ld",(long)indexPath); неверно, это напечатает адрес указателя indexPath

попробуйте использовать следующие коды

CGPoint center= sender.center; 
  CGPoint rootViewPoint = [sender.superview convertPoint:center toView:self.filterTableView];
  NSIndexPath *indexPath = [self.filterTableView indexPathForRowAtPoint:rootViewPoint];
  NSLog(@"%@",indexPath);

Ответ 2

Если у вас есть кнопка в ячейке. Вы можете получить ячейку, вызвав superiew. А затем можно получить Indexpath таким образом.

 (void)obButtonTap:(UIButton *)sender {

    UITableViewCell *cell = (UITableViewCell *)sender.superview;
    NSIndexPath *indexPath = [tableView indexPathForCell:cell];
}

Ответ 3

Быстрое решение: Для этого может быть полезно расширение UITableView, подобное этому.

extension UITableView {
    func indexPathForView(view: AnyObject) -> NSIndexPath? {
        let originInTableView = self.convertPoint(CGPointZero, fromView: (view as! UIView))
        return self.indexPathForRowAtPoint(originInTableView)
    }
}

Использование становится простым во всем мире.

let indexPath = tableView.indexPathForView(button)

Ответ 4

Вы можете назначать теги каждому коммутатору в методе cellForRowAtIndexPath, например

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {    
   UISwitch *accessorySwitch = [[UISwitch alloc]initWithFrame:CGRectZero];
   [accessorySwitch setOn:NO animated:YES];
   [accessorySwitch addTarget:self action:@selector(changeSwitch:) forControlEvents:UIControlEventValueChanged];
   cell.accessoryView = accessorySwitch; 
   accessorySwitch.tag = indexPath.row;    
}

- (void)changeSwitch:(UISwitch *)sender{
    NSIndexPath *indexPath = [NSIndexPath indexPathWithIndex:[sender tag]];
    NSLog(@"%ld",(long)indexPath);
}

Ответ 5

Вероятно, вы сжигаетесь, полагая, что переключатель superview будет tableViewCell. Возможно, в iOS 7 они изменили иерархию, чтобы достичь своего рода визуального эффекта; возможно, там есть новый вид.

Вы могли бы подкласса UISwitch и присвоить ему свойство indexPath. Затем в своем cellForRowAtIndexPath назначьте его там, чтобы у вас была ссылка.

Ответ 6

Я думаю, что опасно полагаться на позицию кнопки, чтобы узнать, какой из них был нажат.

Я предпочитаю создавать словарь, беря в качестве ключа кнопку/сам переключатель, а в качестве значения - путь index:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
...
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    NSValue * accessorySwitchKey = [NSValue valueWithNonretainedObject:[cell settingSwitch]];
    [[self switchIndexDictionary]setObject:indexPath accessorySwitchKey];
...
}

тогда, когда кнопка switch/нажата, я легко получаю индексный путь из моего словаря:

- (void)toggleSetting:(id)sender
{
    UISwitch *selectedSwitch = (UISwitch *) sender;

    NSValue * accessorySwitchKey = [NSValue valueWithNonretainedObject:selectedSwitch];
    NSIndexPath *indexPath = [[self switchIndexDictionary]objectForKey: accessorySwitchKey];
}

Ответ 7

SWIFT 4:

extension UITableView {
    func indexPathForView(view: AnyObject) -> NSIndexPath? {
        let originInTableView = self.convert(CGPoint.zero, from: (view as! UIView))
        return self.indexPathForRow(at: originInTableView)! as NSIndexPath
    }
}