29

プログラムで 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 では nil を出力します。

iOS 7 に何か足りないものがありますか、それとも iOS 7 で indexPath を取得する別の方法があります

ありがとう、アルン。

4

9 に答える 9

8

迅速な解決策: このような 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)
于 2016-08-20T22:28:28.637 に答える
2

スイフト 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
    }
}
于 2017-10-23T12:23:59.297 に答える
0

ボタンの位置だけでどのボタンがクリックされたかを判断するのは危険だと思います。

ボタン/スイッチ自体をキーとして、値として indexpath を取る辞書を作成することをお勧めします。

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

次に、スイッチ/ボタンがトリガーされると、辞書から簡単にインデックスパスを取得します:

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

    NSValue * accessorySwitchKey = [NSValue valueWithNonretainedObject:selectedSwitch];
    NSIndexPath *indexPath = [[self switchIndexDictionary]objectForKey: accessorySwitchKey];
}
于 2015-03-23T16:34:39.733 に答える