2

次のようなUITableViewCellを作成しようとしています。

まだ画像を投稿できないので、UISwitch(中央)とアクセサリー(右)の付いたラベル(左)だと言って説明しようと思います。

あなたが写真を手に入れることを願っています...

アイデアは、accessoryViewは表示されますが、スイッチがオフの場合は無効になるというものです。ユーザーがスイッチをオンにすると、タップして右にナビゲートし、選択できるオプションのリストを表示できます。問題は、スイッチがタップされたときに、セルがスイッチではなくタップを取得することです。

私は何をしなければならないのですか?(スイッチに最初にタップを取得させるため)。ファーストレスポンダーだと思いますが、必要な魔法のコードが見つかりません。

これを乗り越えたら、おそらく自分でアクセサリの有効化/無効化を理解できます...

ありがとう。

4

1 に答える 1

1

UISwitch コントロールを作成し、セル コンテンツ ビューに追加します。

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *CellIdentifier = @"Cell";

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = (UITableViewCellAccessoryNone;
            UISwitch* aSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
aSwitch.tag = [indexPath row];

            CGRect rect = cell.frame;
            CGRect switchRect = aSwitch.frame;
            switchRect.origin = CGPointMake( (rect.size.width / 2) - (aSwitch.frame.size.width / 2), 
                                               (rect.size.height / 2) - (aSwitch.frame.size.height / 2));

            aSwitch.frame = switchRect;
            [aSwitch addTarget:self action:@selector(switchSwitched) forControlEvents:UIControlEventValueChanged];
            [cell addSubview:aSwitch];


            [aSwitch release];
        }

        return cell;
    }

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

        if (sender.on) {

    UITableViewCell* aCell = [self.tableView cellForRowAtIndexPath:
                              [NSIndexPath indexPathForRow:sender.tag inSection:0]];

    aCell.accessoryType = (sender.on == YES ) ? UITableViewCellAccessoryDisclosureIndicator : UITableViewCellAccessoryNone;
        }
    }

UITableViewCell をサブクラス化し、UITableViewCell nib ファイルを追加することで、これを別の方法で実装することもできます。UIViewTableController を Cell nib ファイルのファイル所有者にし、サブクラス化されたセルの IBOutlet を UIViewController に追加します。を使用してカスタムセルをロードします

        [[NSBundle mainBundle] loadNibNamed:@"Your Custom Cell nib file name" owner:self options:nil];

iOS 用の Apple プログラミング ガイドを参照してください

于 2011-12-15T17:07:48.387 に答える