【问题标题】:Close a modal view with a button in Swift?在 Swift 中使用按钮关闭模式视图?
【发布时间】:2020-09-04 09:43:33
【问题描述】:

学习了一些视图控制器的基础知识,并被困在如何使用按钮关闭模式。

在我的精简示例中,我有两个视图设置,初始视图和模态视图。第一个视图有一个成功弹出模态的按钮。在模态框上,有一个应该自行关闭的按钮。

根据other posts 和文档,我应该能够像这样运行附加到按钮的简单代码:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func CloseModal(_ sender: Any) {
        self.dismiss(animated: true, completion: nil)
    }

}

当我点击“关闭模式”按钮时,没有任何反应。我在这里想念什么?我把这段代码放在错误的地方吗?目前,它位于主 ViewController.swift 文件中。

【问题讨论】:

  • 确保您已将 IbAction 与情节提要中的按钮连接
  • @NabeelNazir 是的,我从按钮上进行了控制拖动以创建 IBAction 函数。

标签: swift uiviewcontroller modalviewcontroller dismissviewcontroller


【解决方案1】:

另一种方法是在主视图控制器中使用unwind segue。只需在第一个视图控制器中添加一个“展开动作”:

class ViewController: UIViewController {

    @IBAction func unwindHome(_ segue: UIStoryboardSegue) {
        // this is intentionally blank
    }

}

只要给这个展开动作一个有意义的名字,在这个例子中是unwindHome,这样,如果你以后有多个展开动作时,你可以很容易地区分它们。

然后你可以control-从第二个场景中的按钮拖到“exit”控件并选择合适的展开动作:

这有几个不错的方面:

  • “关闭”按钮不再关心您如何呈现它,它会展开但适当(例如,如果您稍后将初始转场更改为显示/推送转场,展开转场仍然可以在没有任何代码更改)。

  • 因为您现在使用 segue 来展开,所以如果您最终需要这样做,呈现的视图控制器可以使用其 prepare(for:sender:) 发回数据。

  • 如果需要,您可以展开多个场景。例如,如果 A 呈现 B,B 呈现 C,你显然可以从 C 展开到 B,但如果你愿意,你也可以从 C 一直展开到 A。

所以,虽然dismiss 有效,但展开转场是另一种选择。

【讨论】:

  • 这是一个非常好的选择。我现在要试着让它工作。谢谢!
  • 精彩 - 更周到的结束方式!
【解决方案2】:

你实际上有两个 ViewController 屏幕,但看起来你有一个 ViewController 类?第二个屏幕是否连接到一个类?

必须在属于closeModal方法第二屏的类中。

//This is First ViewController, OpenModal Button is here
class ViewController: UIViewController {

  override func viewDidLoad() {
     super.viewDidLoad()
  }

}


// The name of the class and the Viewcontroller in the storyboard have to be the same, and CloseModol Button and function need to be here 
class SecondViewController: UIViewController {

  override func viewDidLoad() {
     super.viewDidLoad()
  }

  @IBAction func CloseModal(_ sender: Any) {
     self.dismiss(animated: true, completion: nil)
  } 

}

不要忘记在 Storyboad 中设置 ViewController 的名称; 从 FirstViewController 到 SecondViewController

【讨论】:

  • 是的。就是这个。 叹息……我要学的东西太多了。谢谢你。另一个问题:即使动画设置为 true,关闭时也没有动画。模态只是消失了。我本来预计它会滑下来(与它滑到视野中的方式相反)。有什么想法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-24
  • 1970-01-01
  • 1970-01-01
  • 2017-05-24
  • 1970-01-01
  • 1970-01-01
  • 2021-04-24
相关资源
最近更新 更多