我正在跟踪游戏分数,游戏分数增加/减少25。
我正在使用UIButton
来显示按钮标签中的分数,使用1手指的轻击手势将分数增加25,然后用2个手指轻击手势将分数减少25
我找不到更加模块化的方式来编写这段代码,唯一可以重复使用每个按钮的功能是:
func setButtonTitleAndIncrement(index: Int, button: UIButton) -> Int {
var index = index
index += 25
button.setTitle(String(index), for: .normal)
return index
}
func setButtonTitleAndDecrement(index: Int, button: UIButton) -> Int {
var index = index
index -= 25
button.setTitle(String(index), for: .normal)
return index
}
但是对于每个按钮,我必须使用相同的代码,除非指定特定的按钮和方法,但我无法找到解决方法。 我希望至少采用一般index
和button
。有什么想法吗?
var index1 = 0
var index2 = 0
override func viewDidLoad() {
super.viewDidLoad()
let oneFingerTapButtonTeam1 = UITapGestureRecognizer(target: self, action: #selector(incrementScoreTeam1))
oneFingerTapButtonTeam1.numberOfTouchesRequired = 1
buttonTeam1.addGestureRecognizer(oneFingerTapButtonTeam1)
let twoFingerTapButtonTeam1 = UITapGestureRecognizer(target: self, action: #selector(decrementScoreTeam1))
twoFingerTapButtonTeam1.numberOfTouchesRequired = 2
buttonTeam1.addGestureRecognizer(twoFingerTapButtonTeam1)
let oneFingerTapButtonTeam2 = UITapGestureRecognizer(target: self, action: #selector(incrementScoreTeam2))
oneFingerTapButtonTeam2.numberOfTouchesRequired = 1
buttonTeam2.addGestureRecognizer(oneFingerTapButtonTeam2)
let twoFingerTapButtonTeam2 = UITapGestureRecognizer(target: self, action: #selector(decrementScoreTeam2))
twoFingerTapButtonTeam2.numberOfTouchesRequired = 2
buttonTeam2.addGestureRecognizer(twoFingerTapButtonTeam2)
}
func incrementScoreTeam1() {
print("1 tapped")
let ind = setButtonTitleAndIncrement(index: index1, button: buttonTeam1)
index1 = ind
}
func incrementScoreTeam2() {
print("2 tapped")
let ind = setButtonTitleAndIncrement(index: index2, button: buttonTeam2)
index2 = ind
}
func decrementScoreTeam1() {
print("1 Two tapped")
let ind = setButtonTitleAndDecrement(index: index1, button: buttonTeam1)
index1 = ind
}
func decrementScoreTeam2() {
print("2 Two tapped")
let ind = setButtonTitleAndDecrement(index: index2, button: buttonTeam2)
index2 = ind
}