2012-02-24 9 views
0
の背景

いただきました次のコードで間違ってUIImageを設定する:これは間違っている場合はUIButton

UIButton *button = [[UIButton alloc]init]; 
    CGRect frame = CGRectMake(180, 10, 33, 33); 
    button.frame = frame; 
    button.tag = 1001; 
    UIImage *image = [[[UIImage alloc]init]autorelease]; 
    image = [UIImage imageNamed:@"icon.png"]; 
    [button setBackgroundImage:image forState:UIControlStateNormal]; 
    [image release]; 
    [button release]; 

どこに補正し、なぜ必要なのでしょうか?

+1

を試すことができますか?あなたはそれを試しましたか?それが動作しているかどうかを知る必要があります。 – smitec

+0

これをIBで行う方がはるかに簡単です。ボタンを作成し、タイプをカスタムに設定して、イメージを設定します。これをプログラムで行う必要がある理由はありますか? – Osiris

+0

私のために働いています。しかし、私は 'UIImage * image = [[UIImage alloc] init] autorelease]と言われました。 image = [UIImage imageNamed:@ "icon.png"]; 'は間違ったアプローチです。 –

答えて

6

私はいくつかの問題を参照してください。

  1. を手動でそれをリリースした後、画像に自動解放を送りました。
  2. ボタンをリリースしましたが、サブビューとして追加しませんでした。だから、基本的に、あなたは何もしなかった。
  3. UIImageをインスタンス化してから、もう一度インスタンス化します。次の行に:代わりに: UIImage *image = [UIImage imageNamed:@"icon.png"]; と削除UIImage *image = [[[UIImage alloc]init]autorelease];とステートメントを実行します。
+1

あなたはまた、以下のlooyaoの答えを見てください! – dbrajkovic

0

imagenilではないことを確認しましたか?

4

あなたはそれが間違っている**場合**この

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
button.frame = CGRectMake(180, 10, 33, 33);; 
button.tag = 1001; 
UIImage *image = [UIImage imageNamed:@"icon.png"]; 
if (image == nil) { 
    NSLog(@"can't find icon.png"); 
} else { 
    [button setBackgroundImage:image forState:UIControlStateNormal]; 
} 
//add button to the parent's view 
+0

よろしくお願いします。私は最初の行を見逃した!もう一つ。 .pngを取り除く。 UIImage * image = [UIImage imageNamed:@ "icon"]; 'そうすれば、RetinaDisplayのアイコン@ 2x(プロジェクトに追加した場合)アイコンが自動的にロードされます – dbrajkovic

+0

これは良い@looyao – Kamarshad