2017-04-12 36 views
1

我有一個自定義的UIButton稱爲RippleButton宣佈像這樣自定義的UIButton觸發IBAction爲一次,然後再也

public class RippleButton: UIButton 

基本上它觸摸時產生了連鎖反應。我使用的是下面的IBAction爲

@IBAction func toggleMic() { 
    if isMicrophoneOn { 
     print("Stopped recording") 
     micIcon.image = UIImage(named: "mic_off") 
     micLabel.text = "Start Recording" 
    } else { 
     print("Started recording") 
     micIcon.image = UIImage(named: "mic_on") 
     micLabel.text = "End Recording" 
    } 

    isMicrophoneOn = !isMicrophoneOn 
} 

的作用是通過對觸摸的內心活動的設計編輯器分配給該按鈕自定義按鈕。

我RippleButton覆蓋的touchesBegan像這樣

override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
    super.touchesBegan(touches, with: event) 
    ripple.animate(sender: self, location: touches.first!.location(in: self)) 
} 

當我觸摸按鈕,它第一次將觸發IBAction爲,並從我的課紋波

func animate(sender: UIView, location: CGPoint){   
    ripple?.transform = CGAffineTransform(scaleX: 1, y: 1) 
    let size = Double(sender.bounds.width) > Double(sender.bounds.height) ? sender.bounds.width : sender.bounds.height 
    ripple?.frame = CGRect(x: location.x - size/2, y: location.y - size/2, width: size, height: size) 
    ripple?.layer.cornerRadius = size/2.0 
    ripple?.alpha = CGFloat(opacity) 
    ripple?.backgroundColor = color 
    ripple?.transform = CGAffineTransform(scaleX: 0, y: 0) 
    container?.frame = CGRect(x: 0, y: 0, width: sender.frame.size.width, height: sender.frame.size.height) 
    container?.layer.cornerRadius = sender.layer.cornerRadius 
    container?.clipsToBounds = true 

    UIView.animate(withDuration: TimeInterval(speed), 
        delay: 0.0, 
        options: .curveEaseOut, 
        animations: { 
        self.ripple?.transform = CGAffineTransform(scaleX: 2.5, y: 2.5) 
        self.ripple?.alpha = 0.0 
    }) 
} 

ripple扮演我的動畫是一個子視圖加入到container,container是添加到RippleButton

的視圖當我碰它時首先觸動動畫,但IBAction不會觸發。爲什麼它會觸發一次,然後再也不會發生?

+0

而不是覆蓋'touchesBegan',爲什麼不直接掛鉤在Interface Builder中'touchDown'事件? –

+0

因爲我不想爲所有使用這個類的按鈕做這件事。因爲我計劃在多個地方使用這個類,所以每次我實現這個類時,都會在IB中接觸'touchDown'的大量重複工作。 – ChrisStillwell

+0

如果你只是使用'UIButton'它是否工作? – Alistra

回答

1

你說「漣漪是添加到容器的子視圖,容器是添加到RippleButton的視圖」...你是否在「漣漪」效果後移除該容器?也許這就是觸摸事件。

+0

這是問題所在。我正在添加容器來填充按鈕,然後攔截觸摸。通過添加'container?.isUserInteractionEnabled = false',我能夠按預期工作。 – ChrisStillwell

0

通過調用self.sendActionsForControlEvents在touchesEnded中默認觸發該操作。嘗試覆蓋touchesEnded和touchesCancelled(使用超級調用)並在兩者中設置斷點。也許該活動將在第二次被取消。在這種情況下,您的動畫會以某種方式干擾內部按鈕狀態的實現。這很難解決,因爲UIButton是一個黑匣子,甚至更糟糕的是它的內部實現可能會改變。那麼你應該從UIControl派生出來。

看看到:4 different ways to handle tap

相關問題