如何在Swift中的UITableViewController中创建navigationBar?

Tim*_*Tim 10 ios swift

我是IOS的新手,

我想补充一UINavigationBarUITableViewController,我已经试过这样:

var navBar: UINavigationBar = UINavigationBar(frame: CGRect(x:0, y:0, width:320, height:80))
Run Code Online (Sandbox Code Playgroud)

然后,

self.view .addSubview(navBar)
Run Code Online (Sandbox Code Playgroud)

谢谢

Ric*_*cky 15

你不能simplly添加NavigationBarUITableViewController这样.

从Storyboard中获取UINavigationController和使用NavigationBar它的最简单方法.

脚步:-

  1. UITableViewController对象从对象库拖到Storyboard.

  2. 突出显示UITableViewController,转到编辑 - >嵌入 - >导航控制器,如下面的屏幕截图所示: - 在此输入图像描述

  3. 转到文件 - >新建 - >文件.. - > iOS - > Cocoa Touch Class,并创建一个自定义TableViewController类,如下面的屏幕截图: - 在此输入图像描述

  4. 最后,返回故事板并突出显示UITableViewController对象.在身份检查器下,选择您刚创建的自定义类,如下面的屏幕截图所示: - 在此输入图像描述

您可以使用自定义类文件执行任何操作.您也可以添加自定义UINavigationController类,以及如果你想和你可以将自定义类在故事板内的对象.


Alb*_*ori 5

如果这仅仅是呈现出的情况下,模式 UITableViewController与一个导航栏,从代码中做到这一点,最简单的方法是提供一个UINavigationController与你UITableViewControllerrootViewController:

呈现视图控制器:

let sourceSelectorTableViewController = SourceSelectorTableViewController()
let navigationController = UINavigationController(rootViewController: sourceSelectorTableViewController)

self.presentViewController(navigationController, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)

目标模态UITableViewController:

override func viewDidLoad() {
    super.viewDidLoad()

    self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: "done")
    self.title = "Pick a Source"
}
func cancel() {
    self.dismissViewControllerAnimated(true, completion: nil)
}

func done() {
    //save things
    self.dismissViewControllerAnimated(true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)