我有这个问题很长一段时间。我试图想象3门问题,只是为了乐趣和练习Swift。所以我有:
3门,因此3个不同的IBAction& 所有门的3个功能。这些功能都完全相同,但每个代码中只有门的数量不同。所以我想知道,我可以缩短这段代码吗?:
func openSecondChoice(whatDoorIsClickedOn: Int)
{
if whatDoorIsClickedOn == 1
{
if whatDoorIsClickedOn == doorWithNumber
{
UIButtonDoor1.setBackgroundImage( UIImage (named: "doorWithMoney"), for: UIControlState.normal)
}
else
{
UIButtonDoor1.setBackgroundImage( UIImage (named: "doorWithGoat"), for: UIControlState.normal)
}
}
if whatDoorIsClickedOn == 2
{
if whatDoorIsClickedOn == doorWithNumber
{
UIButtonDoor2.setBackgroundImage( UIImage (named: "doorWithMoney"), for: UIControlState.normal)
}
else
{
UIButtonDoor2.setBackgroundImage( UIImage (named: "doorWithGoat"), for: UIControlState.normal)
}
}
if whatDoorIsClickedOn == 3
{
if whatDoorIsClickedOn == doorWithNumber
{
UIButtonDoor3.setBackgroundImage( UIImage (named: "doorWithMoney"), for: UIControlState.normal)
}
else
{
UIButtonDoor3.setBackgroundImage( UIImage (named: "doorWithGoat"), for: UIControlState.normal)
}
}
}
育!这段代码太丑了!例如,如果用户按下door1,我正在调用函数“openSecondChoise(whatDoorIsClickedOn:1)”。有没有办法缩短这个?谢谢!我不在这里使用课程,我应该使用它们吗?
答案 0 :(得分:5)
通常,当您使用onCreate
,Fragment
,@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
Bundle bundle = getArguments();
// .. Other initializations
updateViews(bundle);
return rootView;
}
等开始为变量名称添加后缀时,是时候使用数组了。这就是数组的用途。
对于包含1
... 2
的数组3
,您的函数可能如下所示:
uiButtonDoors
答案 1 :(得分:3)
func openSecondChoice(whatDoorIsClickedOn: Int) {
let imageName = whatDoorIsClickedOn == doorWithNumber ? "doorWithMoney" : "doorWithGoat"
let image = UIImage(named: imageName)
let button: UIButton
switch whatDoorIsClickedOn {
case 1:
button = UIButtonDoor1
case 2:
button = UIButtonDoor2
case 3:
button = UIButtonDoor3
default:
fatalError("Cannot be. Switch must be exhaustive, that's why we need to use 'default' for a switch on Int.")
}
button.setBackgroundImage(image, for: .normal)
}
对于较短的版本,请查看@tuple_cat的答案。
答案 2 :(得分:2)
另一种方法,为了好玩。
import UIKit
class DoorGame {
func setupButtons() {
let buttons = [UIButton(), UIButton(), UIButton()]
for (index, button) in buttons.enumerated() {
button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
button.setTitle("\(index)", for: .normal)
}
let winningIndex = Int(arc4random_uniform(UInt32(buttons.count)))
buttons[winningIndex].tag = 1
}
@objc func buttonTapped(_ sender: UIButton) {
let imageName = sender.tag == 1 ? "doorWithMoney" : "doorWithGoat"
let image = UIImage(named: imageName)
sender.setBackgroundImage(image, for: .normal)
}
}