2011-07-13 40 views
38

我想添加子視圖到UIButton。現在工作正常。但是,只要添加子視圖,該按鈕就不再可點擊。addSubView到UIButton

我使用下面的代碼:

UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom]; 
    button.frame = CGRectMake(column*100+24, row*80+10, 64, 64); 
[button addSubview:asyncImage]; 
[button addSubview:price]; 
    [button addTarget:self 
       action:@selector(buttonClicked:) 
    forControlEvents:UIControlEventTouchUpInside]; 

如果我切出的2個addsubviews按鈕再次工作。如果有人知道如何解決這個問題,那就太棒了!

THNX !!!

回答

73

我找到了一個快速解決方案。我需要將asyncimageview設置爲以下內容:

asyncImage.userInteractionEnabled = NO; 
     asyncImage.exclusiveTouch = NO; 

之後它工作!

+0

將盡可能在2天內回答我的問題 – Jos

+0

我想'userInteractionEnabled'屬性的相反,我認爲將其設置爲「YES」應該實際上捕捉按鈕的子視圖上的單擊事件。 GREAT ANSWER! – Shvalb

+0

5個小時後我找到你了!謝謝 ! – YannickSteph

3

嘗試:

[UIButton buttonWithType:UIButtonTypeCustom];

代替:

[UIButton buttonWithType:UIButtonControlType];

+0

這是不行的,它給了我一個錯誤,不承認UIButtonControlType – Jos

+0

哦,然後嘗試用戶交互設置爲啓用,像這[你的按鈕setUserInteractionEnabled://布爾,對你來說,它是YES – user842059

+0

我試圖爲2子視圖(價格和asyncImage)和按鈕。位沒有任何區別... – Jos

1

你有沒有試圖把:

[asyncImage setUserInteractionEnabled:YES]; 
+0

嘗試過,但沒有任何成功... :( – Jos

+0

你有沒有嘗試與其他視圖?[price setUserInteractionEnabled:是]; –

+0

是的,也沒有運氣 – Jos

1

在同一sitiation我做出這個動作: 從...繼承UIButton並添加按鈕的所有標籤和imageview的自我,最後把新的按鈕作爲最後一個子視圖,並添加自我按鈕的目標到最後一個按鈕(也設置backgroundColor clearColor透明)。現在它可以點擊並且正常工作。

+0

我得到某種方式這個想法,但不完全知道我需要做什麼,你有一個簡短的例子嗎?Thnx! – Jos

+0

我主要不明白你的意思是讓動作繼承自UIButton,並將其設置爲self。做self.button它給了我一個錯誤。Thnx! – Jos

+0

我把這裏的例子:[鏈接](http://pastebin.com/r8yQrB0Y) –

1

這裏重要的是要確保userInteractionEnabled將被設置爲NO。幸運的是,它可以立即生效UIImageViewUILabel(可能是UIView的其他子類,但這些是最受歡迎的子視圖添加到按鈕),因爲默認情況下這個類默認設置爲NO。不幸的是,它在UIView中設置爲YES,因此請確保在這種情況下進行更改。與任何其他國旗亂七八糟不應該是必要的。問題的本質是很多人不知道這個標誌的默認值在子類中是不同的。

+0

嗨@朱連,它不適合我... – benhi

+0

@benhi,很酷。如果你想我幫忙 - 更多的細節將會有幫助:P –

+0

Julian @property(弱,非原子)IBOutlet UIButton * popular; popular = [UIButton buttonWithType:UIButtonTypeCustom]; UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,popular.frame.size.width,popular.frame.size.height)]; label.text = @「ButtonTitle」; label.textColor = [UIColor redColor]; label.userInteractionEnabled = NO; [popular addSubview:label]; – benhi

1

在斯威夫特,測試是你有你的UIButton封鎖

uibtn.userInteractionEnabled = false 
uibtn.exclusiveTouch = false