我正在尝试创建一个uitableviewcontroller作为模态viewcontroller来编辑一些设置。我在代码中创建tableviewcontroller,我正在努力解决的问题是如何正确地向控制器添加导航栏,控制器上有一个“完成”按钮:
a)没有出现在tableview的顶部 b)不用tableview滚动??
当我将导航栏添加到控制器时会发生以下情况: [self.view addSubview:navigationBar]; 这会向控制器添加一个导航栏,它会在顶部显示并遮挡第一行的表格并同时滚动视图?
我还想过简单地使用带有单独tableview的uiviewcontroller但是我喜欢在编辑tableviewcontroller给你的文本字段时自动滚动tableview的功能。只是不知道如何设置这个导航栏??
THX
答案 0 :(得分:9)
只需创建UINavigationcontroller作为模态视图控制器,并将tableview添加为其根视图控制器。
答案 1 :(得分:6)
使用导航控制器作为modalviewController(如另一个答案所示)。这是代码:
UINavigationController *Controller = [[UINavigationController alloc] init];
//LoginViewController is a sub class of UITableviewController
LoginViewController *controller = [[LoginViewController alloc] init];
Controller.viewControllers=[NSArray arrayWithObject:controller];
[self presentModalViewController:Controller animated:YES];
[controller release];
[Controller release];
答案 2 :(得分:0)
在 Swift :
<强> AppDelegate.swift 强>
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
/*
#1. Instantiate a navigation controller and add the table view controller
as a child view controller.
*/
let navigationController = UINavigationController()
// Instantiate your desired ViewController
let storyboard = UIStoryboard(name: UIStoryboardName.Main.rawValue, bundle: nil)
let tableViewController = storyboard.instantiateViewControllerWithIdentifier("TableViewControllerID")
navigationController.addChildViewController(tableViewController)
/*
#2. Then we set the title of the navigation bar and add two bar button items.
*/
// We set the title of the navigation bar.
tableViewController.navigationItem.title = "My Title"
// Create left and right button for navigation item.
let leftButton = UIBarButtonItem(title: "Save", style: UIBarButtonItemStyle.Plain, target: tableViewController, action: "saveButtonClicked:")
let rightButton = UIBarButtonItem(title: "Right", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
// Create two buttons for the navigation item.
tableViewController.navigationItem.leftBarButtonItem = leftButton
tableViewController.navigationItem.rightBarButtonItem = rightButton
/*
#3. To finish we set the root view controller with the navigation controller.
*/
self.window?.rootViewController = navigationController
self.window?.makeKeyAndVisible()
return true
}
<强> TableViewController.swift 强>
// Method called when the user clicks on the Save bar button item.
func saveButtonClicked(sender: UIBarButtonItem) {
// Do something.
print("Save bar button item has been clicked!!!")
}