2009-06-11 36 views
4

如果我有一個UIImageView,並且想知道用戶是否點擊了圖像。在touchesBegan中,我做了以下事情,但總是以第一個條件結束。窗口處於縱向模式,圖像位於底部。我可以點擊窗口右上角,然後進入第一個條件,這看起來很不正確。點不是矩形但CGRectContainsPoint說是

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
UITouch *touch = [touches anyObject]; 
CGPoint location = [touch locationInView:touch.view]; 

if(CGRectContainsPoint(myimage.frame, location) == 0){ 
//always end up here 
} 
else 
{ //user didn't tap inside image} 

和值:

location: x=303,y=102 
frame: origin=(x=210,y=394) size=(width=90, height=15) 

有什麼建議?

回答

19

首先,你得到的觸摸與:

UITouch *touch = [[event allTouches] anyObject]; 

接下來,要進行檢查的locationInView相對於圖像視圖。

CGPoint location = [touch locationInView:self]; // or possibly myimage instead of self. 

接着,CGRectContainsPoint返回一個布爾值,所以它比較0是很奇怪。它應該是:

if (CGRectContainsPoint(myimage.frame, location)) { 
    // inside 
} else { 
    // outside 
} 

但是如果自我不是那麼MYIMAGE的MYIMAGE觀點可能得到觸摸,而不是你 - 它不是從你的問題是什麼對象自我是很明顯不是的UIImageView的子類題。

4

你的邏輯很簡單。 CGRectContainsPoint()方法返回bool,即對「是」返回true。真不等於0

+0

0在C中總是爲false。在任何計算環境中幾乎都不是真的(我想不出任何使用0的語言作爲True,儘管可能有一個)。 – Chuck 2009-06-11 06:46:00

+0

@Chuck:當然,但有些情況下0表示「(成功)」(如strcmp()),這就是我爲什麼這樣寫的原因。 – unwind 2009-06-11 08:13:58