问题:
我有一个UIButton,当用户没有触摸屏幕并在用户触摸屏幕时将其淡入时,我想淡出几秒钟。我想我可能需要在viewdidload部分中使用计时器和一些动画
@IBOutlet var startStopButton: UIButton!
@IBAction func startStopButtonTapped(_ sender: UIButton) {
}
override func viewDidLoad() {
super.viewDidLoad() }
答案 0 :(得分:0)
我可以在这里帮助你。让我以可用性问题为前提这个答案。我不确定在X秒后点击屏幕上的任何地方重置(淡入)按钮是否有意义(用户是否知道这样做?)。您可能需要添加一个按钮或某种文本指示符,然后点击此处重置按钮"。这一切最终取决于你的应用程序,但只是把它丢弃在那里:)
接着回答!
这里的一般想法是你想拥有一个每1秒运行一次方法的计时器。如果计时器达到零,则淡出并禁用startStop按钮。如果用户点击屏幕上的任何位置(通过整个视图上的手势识别器),则淡入按钮并启用它。
现在是代码部分!
class ViewController: UIViewController {
// Create these 3 properties in the top of your class
var secondToFadeOut = 5 // How many second do you want the view to idle before the button fades. You can change this to whatever you'd like.
var timer = Timer() // Create the timer!
var isTimerRunning: Bool = false // Need this to prevent multiple timers from running at the same time.
@IBOutlet weak var startStopButton: UIButton! // The outlet for your button. This is used to fade it in and out, and enable / disable it.
override func viewDidLoad() {
super.viewDidLoad()
startStopButton.isEnabled = true
runTimer()
// Add a tap gesture recognizer to the main view to determine when the screen was tapped (for the purpose of resetting the timer).
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.tap(_:)))
self.view.addGestureRecognizer(tapRecognizer)
}
func runTimer() {
// Create the timer to run a method (in this case... updateTimer) every 1 second.
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(ViewController.updateTimer)), userInfo: nil, repeats: true)
// Set the isTimerRunning bool to true
isTimerRunning = true
}
@objc func updateTimer() {
// Every 1 second that this method runs, 1 second will be chopped off the secondToFadeOut property. If that hits 0 (< 1), then run the fadeOutButton and invalidate the timer so it stops running.
secondToFadeOut -= 1
print(secondToFadeOut)
if secondToFadeOut < 1 {
fadeOutButton()
timer.invalidate()
isTimerRunning = false
}
}
@objc func tap(_ gestureRecognizer: UITapGestureRecognizer) {
// When the view is tapped (based on the gesture recognizer), reset the secondToFadeOut property, fade in (and enable) the button.
//secondToFadeOut = 5
fadeInButton()
timer.invalidate()
//if isTimerRunning == false {
// runTimer()
//}
}
func fadeOutButton() {
// Fade out your button! I also disabled it here. But you can do whatever your little heart desires.
UIView.animate(withDuration: 0.5) {
self.startStopButton.alpha = 0.25
}
self.startStopButton.isEnabled = false
}
func fadeInButton() {
// Fade the button back in, and set it back to active (so it's tappable)
UIView.animate(withDuration: 0.5) {
self.startStopButton.alpha = 1
}
self.startStopButton.isEnabled = true
}
@IBAction func startStopButtonPressed(_ sender: UIButton) {
print("Start Stop Button Pressed")
}
}
希望这是有道理的,但如果你有任何其他问题,请告诉我!