Xcode:重置应用程序以及所有变量和类

时间:2019-12-24 16:58:03

标签: swift xcode swift4.2

我有一个应用程序,可以在情节提要板上创建21个按钮,然后这些按钮允许用户选择播放器。这些按钮是通过编程方式创建的,并具有设置其格式的类。

//run 2 loops to dsip;ay the buttons (21 of them)
    for j in 0...2 {
    for i in 0...6 {
     //use the CLASS KSPIckButton to format the buttons
     let buttonOne:UIButton = KSPickButton(frame: CGRect(x: (j + 1) * 35 + (j * 80), y: (i + 5) * 35 + buttonSet, width: 110, height: 30))


    //Add the button to the storyboard
    self.view.addSubview(buttonOne)


        buttonOne.addTarget(self,
        action: #selector(playerButtons),
        for: .touchUpInside)
    //assign the tag to the button
    buttonOne.tag = playerNo
    //Give the buttons the players names
    buttonOne.setTitle(allPlayers[playerNo], for: .normal)

问题: 用户可以选择10个名称,然后决定重设.....

我尝试: 我从一个动作按钮运行viewDidLoad(),它将在已经存在的21个按钮的顶部再加载另外21个按钮,这在理论上是可行的,但是由于我的按钮的backgroundColor清除了显示下方的旧按钮。

理论: 我想我还是应该不只是加载图层和按钮的图层?

但是我找不到任何地方以编程方式将应用程序重置为刚加载时一样的选项,或者清除现有按钮以便创建更多内容。

问题: 有人可以指出正确的方向来进行应用重置或类似的操作吗?

非常感谢

Kev

2 个答案:

答案 0 :(得分:2)

创建一个reset方法,首先从视图中删除所有可能的选择按钮。

func reset() {
    let ksPickButtons = view.subviews.filter{$0 is KSPickButton}
    ksPickButtons.forEach{$0.removeFromSuperview()}

    // code to create the buttons
}

或更短

func reset() {
    view.subviews.filter{$0 is KSPickButton}
                 .forEach{$0.removeFromSuperview()}

    // code to create the buttons
}

然后将其他代码从viewDidLoad移到reset,并从viewDidLoad以及其他任何位置调用该方法。

旁注:

您不得调用任何包含willdidshould的委托方法。这些方法仅由框架调用。

答案 1 :(得分:0)

您应该只在情节提要上添加按钮并创建IBOutlet以通过代码访问它们,或者不要在情节提要中添加任何按钮并仅使用代码创建和添加它们。我不确定您要完成什么,很遗憾,我无法就此提供很多建议,除了(通常)仅坚持故事板或仅以编程方式创建UI(通常)是一个好主意。我自己更喜欢后者)。

无论哪种方式,要直接回答您的问题,真正“重置”视图控制器的唯一方法是创建一个新的视图控制器,并用新的视图控制器替换旧的(因此,在现有的显示器上实际上没有任何类型的重置)视图控制器)。如果您不想创建新的ViewController,那么您唯一可以做的就是自己手动清理所有内容,我将举一个如何清理按钮的示例:

class Results
{
    sum(numbers){
      let result=numbers.reduce((a,b)=>a+b);
      return result;
    }

    state(numbers){
      console.log(this);
      let result= this.sum(numbers)>0 ? "positive" : "negative";
      return result;
    }
}

function play(){
    let results=new Results(); 

    let numbers=[1,2,3,4];

    console.log(results.sum(numbers));
    console.log(results.state(numbers));

    let arrayfunctions=[];

    arrayfunctions.push(results.sum);
    arrayfunctions.push(results.state);

    arrayfunctions.forEach(funcion=>
    {
        console.log(funcion(numbers))
    });
}

此方法将直接在viewcontroller中的所有视图(因此只有1层深度)过滤到仅KSPickButtons(compactMap),然后循环遍历所有视图以将其从其父视图中移除(forEach)