2010-07-24 117 views
1

我怎樣才能讓圖像在被觸摸時消失。可可觸摸 - 在UIImageView中觸摸

這是我的代碼來創建圖像。它隨機顯示在屏幕上,因此在您觸摸它後,它會消失,並在新位置出現新圖像。

-(void)drawStarsAndDetectTouches{ //uses random numbers to display a star on screen 
    //create random position 
    int xCoordinate = arc4random() % 267; 
    int yCoordinate = arc4random() % 420; 

    //make sure it doesnt draw onto titiles 
    if (yCoordinate <= 40) { 
     yCoordinate = arc4random() % 420; 
    } 

    UIImageView *starImgView = [[UIImageView alloc] initWithFrame:CGRectMake(xCoordinate, yCoordinate, 58, 40)]; //create ImageView 
    starImgView.image = [UIImage imageNamed:@"star.png"]; 

    [self.view addSubview: starImgView]; 

    [starImgView release]; 
} 

回答

1

從我的頭頂,我可以想出兩種方法可以實現這一點。可以使用UIButton而不是UIImageView。在Interface Builder中將按鈕的類型設置爲「自定義」,並選擇圖像作爲按鈕的背景圖像。將一個IBAction指定給該按鈕,並使其不可見。

如果 - 無論出於何種原因 - 您必須堅持使用UIImageView,請創建一個覆蓋-touchesBegan:inView:的子類。此外,請確保您將圖像視圖的userInteractionEnabled屬性設置爲YES,以便每當用戶觸摸視圖時調用-touchesBegan:inView:選擇器。 UIImageView該屬性的默認值爲NO,所以最後一步很重要!這裏

更新是一些示例代碼,以幫助您開始使用的情況下,你需要以編程方式做到這一點按鈕的方法:如果我想使用一個自定義按鈕

UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom]; 
[btn setBackgroundImage:img forState:UIControlStateNormal]; 
[btn addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside]; 

[self.view addSubview:btn]; 
+0

(似乎更容易),我可以編輯我的上面的代碼是一個按鈕?因爲它需要全部編程完成 – user377419 2010-07-24 15:16:09

+1

是的,這應該工作。我認爲你可以做一些類似於我剛剛編輯的答案。 – Benjamin 2010-07-24 18:02:27