2017-08-02 90 views
0

我是新來的斯威夫特,我試圖讓定時器(在標籤),開始與長按按鈕。同時我想在長按按鈕時更改長按按鈕圖像。我離開按鈕,我想讓按鈕恢復。長按識別手勢通過按鈕 - 斯威夫特3

什麼可能是錯誤的?

@IBOutlet weak var myBtn: UIButton! 

func initGesture() 
{ 

    { let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(longTap(_:))) 
     myBtn.addGestureRecognizer(longGesture) 
    } 
} 

func TimerAction() 
{ 
    Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(longTap), userInfo: nil, repeats: false) 
    myBtn.setImage(UIImage(named: "xxx.png"), for: .normal) 


} 
@IBOutlet weak var lbl: UILabel! 

func start() 
{ 
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(ViewController2.updateTime as (ViewController2) ->() ->())), userInfo: nil, repeats: true) 

} 

func updateTimer() { 
    count += 1 
    let hours = Int(count)/3600 
    let minutes = Int(count)/60 % 60 
    let seconds = Int(count) % 60 
    label.text = String(format: "%02i:%02i:%02i",hours,minutes,seconds) 
} 

func reset() 
{ 
    timer.invalidate() 
    count = 0 
    label.text = "00:00:00" 

} 
+0

什麼是你的代碼做exaclt? –

+0

我正在努力做一些我寫的東西。我用長按手勢識別敲了myBtn。我在哪裏錯了? @MohammadBashirSidani – MarryJoe

+0

https://stackoverflow.com/questions/34548263/swift-button-tap-and-long-press-gesture – Eridana

回答

5

你可以得到TouchUpInside和TouchUpOutside還按鈕的TouchDown的動作不使用手勢。

class ViewController: UIViewController { 
@IBOutlet weak var lbl: UILabel! 
@IBOutlet weak var myBtn: UIButton! 
var timer: NSTimer! 

override func viewDidLoad() { 
     super.viewDidLoad() 
     myBtn.addTarget(self, action: "buttonDown:", forControlEvents: .TouchDown) 
     myBtn.addTarget(self, action: "buttonUp:", forControlEvents: [.TouchUpInside, .TouchUpOutside]) 
    } 
func buttonDown(sender: AnyObject) { 
    singleFire() 
    timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "rapidFire", userInfo: nil, repeats: true) 
} 

func buttonUp(sender: AnyObject) { 
    timer.invalidate() 
    count = 0 
    label.text = "00:00:00" 
} 

func singleFire() { 
    myBtn.setImage(UIImage(named: "xxx.png"), for: .normal) 
} 

func rapidFire() { 
    count += 1 
    let hours = Int(count)/3600 
    let minutes = Int(count)/60 % 60 
    let seconds = Int(count) % 60 
    label.text = String(format: "%02i:%02i:%02i",hours,minutes,seconds) 
} 

} 
+0

不錯的一個。但它增加了識別長按的代碼。 – jegadeesh

+0

@jegadeesh感謝您的建議,但我展示了行動的用途。 –

+0

非常感謝!有用! @SalmanGhumsani – MarryJoe

1

您應該實現按鈕事件,而不是在這裏使用手勢識別器。我談論的按鈕事件是TouchDown和TouchUpInside。 TouchDown會告訴你什麼時候按下按鈕,並且touchupinside會告訴你用戶何時按下按鈕。

因此,您將更改按鈕圖像並在觸地事件時啓動計時器。然後你會恢復touchupinside事件。

https://developer.apple.com/documentation/uikit/uicontrolevents

0

嘗試此,

組第一取決於其狀態的按鈕的圖像。

self.arrowIcon.setImage(UIImage(named: "normalImage.png"), for: .normal) 
    self.arrowIcon.setImage(UIImage(named: "pressedImage.png"), for: .highlighted) 
+0

謝謝!我用你的代碼,它的工作! @Kiester – MarryJoe

+0

很高興幫助@MarryJoe! – Kiester