swift2 如何创建取消按钮?

bf1o4zei  于 2022-11-06  发布在  Swift
关注(0)|答案(4)|浏览(227)

我有麻烦让我的取消按钮工作。我有这个动作连接到我的取消按钮,我计划这样关闭视图控制器:

@IBAction func cancel(sender: UIBarButtonItem) {
     dismissViewControllerAnimated(true, completion: nil)
}

我想知道我错过了什么明显的位。(这是一个表视图的栏按钮项)。

luaexgnf

luaexgnf1#

var b = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: "Cancel clicked")

如果希望该方法将sender作为参数,则应在结尾处放置冒号:

var b = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: "CancelClicked:")

func CancelClicked(sender: UIBarButtonItem) {
}
g52tjvyc

g52tjvyc2#

使用IB将NavigationBar(和NavigationItem)添加到情节提要后,对navigationItem var的引用将自动Map到ViewController文件。添加下面的代码以将取消按钮附加到navigationItem,从而消除模态视图控制器:

@IBOutlet weak var navigationBar: UINavigationBar!

override func viewDidLoad() {
    super.viewDidLoad()
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelClicked(sender:)))
}

func cancelClicked(sender: UIBarButtonItem) {
    print("Cancel clicked!")
    self.dismiss(animated: true, completion: nil)
}
sc4hvdpw

sc4hvdpw3#

试试看:

@IBAction func close(sender: AnyObject) {
    self.dismissViewControllerAnimated(true, completion: nil)
}
wfypjpf4

wfypjpf44#

您的代码在一个小的修复后工作正常。Dismiss是在呈现控制器上调用的。self.dismissViewController将解除当前vc呈现的子视图控制器。但如果您想解除现有vc,则应在父视图控制器上调用dismiss

@IBAction func cancel(sender: UIBarButtonItem) {
      presentingViewController.dismissViewControllerAnimated(true, completion: nil)
}

相关问题