1

cell1、cell2、cell3、cell4 という名前の 4 つのボタンを作成しました。次の for ループで背景画像を設定しようとしています。セル 1、2、および 4 は、背景イメージで正常に読み込まれます。cell3 について次のメッセージを受け取りました。すべてのセルは同じように作成され、各ボタンのタグは 1、2、3、および 4 に設定されました。

なぜcell3(ボタン)が読み込まれないのか途方に暮れています。このトピックに関する同様の以前に回答された質問を確認しましたが、空白を描いています。

失敗しているコードは次のとおりです。

for (int i = 1; i <= 4; ++i) {
    UIButton *cellIndex = (UIButton *)([self.view viewWithTag:i]);
    NSLog(@"==> viewDidLoad cellIndex1 = (%i)", cellIndex.tag);
    [cellIndex setBackgroundImage:[UIImage imageNamed:@"L0background.png"] forState:UIControlStateNormal]; 
} 

バックグラウンド ロードの結果は次のとおりです。

2013-08-30 09:50:07.898 match[863:11f03] ==> viewDidLoad cellIndex1 = (1)
2013-08-30 09:50:07.899 match[863:11f03] ==> viewDidLoad cellIndex1 = (2)
2013-08-30 09:50:07.899 match[863:11f03] ==> viewDidLoad cellIndex1 = (3)
2013-08-30 09:50:07.900 match[863:11f03] -[UIView setBackgroundImage:forState:]: unrecognized selector sent to instance 0x7d68230
2013-08-30 09:50:07.901 match[863:11f03] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView setBackgroundImage:forState:]: unrecognized selector sent to instance 0x7d68230'
*** First throw call stack:
(0x1912012 0x1695e7e 0x199d4bd 0x1901bbc 0x190194e 0x27bf 0x6bb1c7 0x6bb232 0x60a3d5 0x60a76f 0x60a905 0x613917 0x22f5 0x5d7157 0x5d7747 0x5d894b 0x5e9cb5 0x5eabeb 0x5dc698 0x277ddf9 0x277dad0 0x1887bf5 0x1887962 0x18b8bb6 0x18b7f44 0x18b7e1b 0x5d817a 0x5d9ffc 0x202d 0x1f55 0x1)
libc++abi.dylib: terminate called throwing an exception
(lldb) 
4

3 に答える 3

1

cellIndex はforループ内で宣言されています。forループに対してローカルです。forcellIndex オブジェクトの知識がないループの外側に背景画像を設定しようとしています。forそのループの外で cellIndex オブジェクトを宣言しましたか? そうでない場合は、forループ内に背景画像を設定する必要があります。

于 2013-08-30T14:38:09.837 に答える
0

他の人が言ったようUIViewに、問題の方法には反応しません。インデックス 4 のオブジェクトは UIButton ではありません。

このクラッシュを防ぐには、次のようにします。

UIButton *buttonObject;
for (int i = 1; i <= 4; ++i) {
    id cellIndex = [self.view viewWithTag:i];
    if ([cellIndex isKindOfClass:[UIButton class]]) {
        buttonObject = (UIButton *)cellIndex;
        NSLog(@"==> viewDidLoad cellIndex1 = (%i)", cellIndex.tag);
        [buttonObject setBackgroundImage:[UIImage imageNamed:@"L0background.png"] forState:UIControlStateNormal];
    } else {
        NSLog(@"Not a button, returned %@",[cellIndex class]);
    }
} 
于 2013-08-30T16:59:46.160 に答える