所以基本上我想创建一个键盘,当用户点击一个字母时会发生一些事情:
@IBAction func letterBtn(sender: UIButton) { // All the letter buttons are linked to this func.
switch sender.currentTitle! {
case "A":
moveLetters(sender)
case "B":
moveLetters(sender)
case "C":
moveLetters(sender)
case "D":
moveLetters(sender)
case "E":
moveLetters(sender)
case "F":
moveLetters(sender)
case "G":
moveLetters(sender)
default :
println("Error")
}
}
func animateLetter (pos: UILabel, btn: UIButton) { // Make the letter move towards a label.
UIView.animateWithDuration(0.5, animations: { () -> Void in
btn.center = pos.center
})
}
func moveLetters (btn: UIButton) { // Determine which label the pressed letter should move towards.
switch emptyPos.count {
case 1:
animateLetter(pos1, btn: btn)
emptyPos.append(0)
case 2:
animateLetter(pos2, btn: btn)
emptyPos.append(0)
case 3:
animateLetter(pos3, btn: btn)
emptyPos.append(0)
case 4:
animateLetter(pos4, btn: btn)
emptyPos.append(0)
default:
println("Error")
}
}
我发现自己使用多个开关案例,基本上在两个不同的功能中做同样的事情,我想知道是否有比使用26个案例更好的方法整个字母表,以及我的其他功能。
答案 0 :(得分:4)
首先,您可以combine个案例:
switch sender.currentTitle! {
case "A", "B", "C": ... etc
// do something
其次,switch语句允许intervals,通过查看按钮标题的第一个字符可以从中获利:
switch sender.currentTitle![0] {
case "A"..."Z":
// do something
}
至于你的其他问题,我给每个标签一个标签(pos1.tag = 1,pos2.tag = 2)等,并使用viewWithTag功能来获得正确的标签。< / p>
答案 1 :(得分:1)
@Glorfindel回答"A"..."Z"
范围很好。您也可以使用NSRegularExpression
执行此操作:
let regex = try! NSRegularExpression(pattern: "^[A-Z]", options: .CaseInsensitive)
let range = NSMakeRange(0, distance(str.startIndex, str.endIndex))
if let match = regex.firstMatchInString(str, options: .ReportCompletion, range: range) {
// Do something
}