簡體   English   中英

iOS操作:將UIButton添加到另一個UIButton時出現@selector問題。 動作僅適用於按鈕相交的位置

[英]iOS action:@selector issue when UIButton is added to another UIButton. Action only works where buttons intersect

我有一個添加到UIButton1的UIButton2:

按鈕相交

僅在UIButton2與UIButton1(“b”)相交時才調用@selector動作。 因此,在“a”或“c”區域中點擊,操作方法(addDockButtonTouchedDown)不會被調用,但是當您點擊“b”部分時它會被調用。 這是一些代碼:

    // button1 is created elsewhere in the code and is a subclass of UIButton for UI layout (has a footer label and title label set). nothing fancy going on.  button1 userInteractionEnabled is set to yes 
    // button2 is below... 
    NSString *dockPath = [[NSBundle mainBundle] pathForResource:@"AddToMyDock" ofType:@"png"];
    UIImage *dockImage = [UIImage imageWithContentsOfFile:dockPath];
    CGRect rect = CGRectMake(-20.0f, -10.0f + dockImage.size.height+1, dockImage.size.width, dockImage.size.height);
    UIButton *button2 = [[UIButton alloc] initWithFrame:rect];
    button2.userInteractionEnabled = YES;
    button2.exclusiveTouch = YES;
    [button2 setBackgroundImage:dockImage forState:UIControlStateNormal];
    [button2 addTarget:self action:@selector(addDockButtonTouchedDown:)
         forControlEvents:UIControlEventTouchDown];
    [button1 addSubview:button2];

任何想法為什么會發生這種情況以及如何解決它? 請不要建議簡單地將button1做大。

首先,添加一個按鈕作為另一個按鈕的子視圖並不是真正常見的設計,我會避免這樣做。 只需創建一個容納兩個按鈕的容器UIView。

您看到的問題是因為當您的按鈕可能超出其超級視圖的邊界(另一個按鈕)時,將不會注冊button1邊界外部的操作。 您可以看到button2的唯一原因是因為clipsToBounds在button1上設置為NO ,這允許其子視圖在其邊界之外繪制。

因此,使當前解決方案正常工作的唯一方法就是使button1更大。 但是,更好的選擇是創建超級視圖,該視圖足以容納兩個按鈕,並為其添加兩個按鈕。

它不適用於“a”和“c”區域,因為觸摸事件的命中測試在調用button1時失敗。 您應該為button1子類化UIButton並使用以下內容覆蓋命中測試:

 - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    if(CGRectContainsPoint(self.childButton.frame, point)) {
        return [self.childButton hitTest:[self convertPoint:point toView:self.childButton] withEvent:event];
    }
    return [super hitTest:point withEvent:event];
 }

注意:childButton在您的示例中是button2。

注2:我認為不過這應該有效,這是一個設計問題的跡象,但這是你的事。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM