提问者:小点点

在开始时迅速添加标签,并在按下按钮后删除它


这款应用目前以黑色背景开始。我想要一个在黑色背景上写着“警告可能会导致癫痫发作”的标签,一旦屏幕被按下,标签就会消失。这真的很简单,但我是新手

import UIKit

class ViewController: UIViewController {
    let colors: [UIColor] = [
        .systemYellow,
        .systemGreen,
        .systemPurple,
        .systemPink,
        .systemRed,
        .systemBlue,
        .systemOrange,
        .magenta, .darkGray, .gray, .lightGray, .brown, .cyan
    ]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .clear
    
    }
    
    @IBAction func didTapButton() {
        let color1 = self.colors.randomElement()
        let color2 = self.colors.randomElement()
        
        self.view.layer.removeAllAnimations()
        self.view.backgroundColor = color1 /// set to color1
        UIView.animate(withDuration: 1/25, delay: 0, options: [.repeat, .autoreverse, .allowUserInteraction]) {
            self.view.backgroundColor = .black
            self.view.backgroundColor = color2// now animate to color2, reverse, then repeat
        }
    }
    
}

共1个答案

匿名用户

这是假设你按下的按钮有你描述的标签(从你过去的问题看像是案例)。

@IBAction func didTapButton(_ sender: UIButton) { //<-- Here
    sender.isHidden = true //<-- Here
    let color1 = self.colors.randomElement()
    let color2 = self.colors.randomElement()
    
    self.view.layer.removeAllAnimations()
    self.view.backgroundColor = color1 /// set to color1
    UIView.animate(withDuration: 1/25, delay: 0, options: [.repeat, .autoreverse, .allowUserInteraction]) {
        self.view.backgroundColor = .black
        self.view.backgroundColor = color2// now animate to color2, reverse, then repeat
    }
  }
}

如果它是一个不同的按钮/标签,您可以在@IBOutlet处与Interface Builder中的UIButton/UILabel挂钩,并使用.ishidden=true的相同技术来隐藏它。