我想要一个可以检测到手指触摸的应用。如果应用检测到屏幕被点击,我想在那个地方放置一个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
}
}
每当新用户触摸屏幕时,用户Int将在用户Int上计算1个用户。我有一个函数可以检查当你有x个用户时需要做什么,称为“check_users()”。这段代码的问题是,如果你用2个人触摸屏幕,那么用户Int将是2.如果你用3个人触摸屏幕,那么用户Int将是2,然后通过check_users()函数然后通过check_users()函数与用户Int = 3.我希望应用程序在通过带有最终用户Int值的users_check()函数之前等待几秒钟。有谁知道怎么做?
答案 0 :(得分:0)
您可以使用方法执行延迟选择器。在延迟使用后调用方法:
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)
...
}