我想要一个应用程序来检测您的手指何时触摸。如果应用程序检测到屏幕被点击,我想在该位置放置一个 UIImage。该应用程序需要有多个用户。到目前为止我有这个:
var users = 0
@IBOutlet weak var Person_1: UIImageView!
@IBOutlet weak var Person_2: UIImageView!
@IBOutlet weak var Person_3: UIImageView!
@IBOutlet weak var Person_4: UIImageView!
@IBOutlet weak var Person_5: UIImageView!
var fingers = [String?](repeating: nil, count:5)
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
for touch in touches{
let point = touch.location(in: self.view)
for (index,finger) in fingers.enumerated() {
if finger == nil {
fingers[index] = String(format: "%p", touch)
print("finger \(index+1): x= \(point.x) , y= \(point.y)")
if index == 0 {
Person_1.center = CGPoint(x: point.x , y: point.y)
Person_1.isHidden = false
users = 1
}
if index == 1 {
Person_2.center = CGPoint(x: point.x , y: point.y)
Person_2.isHidden = false
users = 2
}
if index == 2 {
Person_3.center = CGPoint(x: point.x , y: point.y)
Person_3.isHidden = false
users = 3
}
if index == 3 {
Person_4.center = CGPoint(x: point.x , y: point.y)
Person_4.isHidden = false
users = 4
}
if index == 4 {
Person_5.center = CGPoint(x: point.x , y: point.y)
Person_5.isHidden = false
users = 5
}
print("Users: \(users)")
break
}
}
}
check_users()
}
func check_users(){
if users == 5 {
let timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(self.choosewinner4), userInfo: nil, repeats: false)
}
if users == 4 {
let timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(self.choosewinner3), userInfo: nil, repeats: false)
}
if users == 3 {
let timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(self.choosewinner2), userInfo: nil, repeats: false)
}
if users == 2 {
let timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(self.choosewinner1), userInfo: nil, repeats: false)
}
}
@objc func choosewinner1(){
let diceRoll1 = Int(arc4random_uniform(2) + 1)
print(diceRoll1)
if diceRoll1 == 1 {
Person_1.isHidden = true
}
if diceRoll1 == 2{
Person_2.isHidden = true
}
}
每次新用户触摸屏幕时,users Int 都会在 users Int 上计数 1 个用户。我有一个函数,可以检查当您有 x 个用户时需要做什么,称为“check_users()”。这段代码的问题是,如果你有 2 个人触摸屏幕,users Int 将是 2。如果你有 3 个人触摸屏幕,users Int 将首先是 2,然后通过 check_users() 函数,然后使用 users Int = 3 执行 check_users() 函数。我希望应用程序等待几秒钟,然后再使用最终的 users Int 值执行 users_check() 函数。有人知道该怎么做吗?
最佳答案
您可以使用延迟执行选择器的方法。要在延迟后调用方法,请使用:
perform(#selector(check_users), with: nil, afterDelay: 1)
要取消任何先前尚未满足的请求:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
NSObject.cancelPreviousPerformRequests(withTarget: self)
...
}
关于swift - TouchBegan 函数的计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50006247/