【发布时间】:2017-02-23 21:11:20
【问题描述】:
我正在跟踪游戏分数,其中游戏分数增加/减少 25。
我正在使用UIButtons 在按钮标签中显示分数,用 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
}
【问题讨论】:
-
您为什么坚持使用 UIButton 以及尝试覆盖事物所带来的所有并发症?只需使用您的标签和设计创建自定义 UIView 子类,然后将手势附加到它。不需要所有的绒毛。
-
@Sneak 我没有坚持任何事情,发布问题是为了找到更好的方法,所以你的建议对我来说很有意义。我刚开始时认为 UIButton 可能是最好的,但现在我正在重新考虑。谢谢!
-
我明白了,使用 UIView 子类,您将从头开始进行许多简单的自定义,而不是覆盖我建议的东西并找到限制。总帐。
-
@Sneak 真棒。感谢您提供的信息,这是我还没有想到的那种方式!
标签: ios iphone swift uibutton uitapgesturerecognizer