简体   繁体   中英

Call viewController from xib

I have a .xib containing a bottom bar view. It has a button that shows a view. I use that bottom bar in almost every view controller and I can't make it work even after searching for over two hours.

Clicking in the bottom bar is working fine ( NSLog shows that the button actions are being called when I click them), but I can't find a way to do what I want. The button needs to show a UITableViewController with 6-7 rows in a specific frame so I don't want to fully use the screen.

|------|
|      |
|      |
|      |
|      |
|______|
|+_____|

|------|
|      |
|      |
|------|
| here |
|______|
|+_____|

In the above figure, the "+" sign is the button, and it needs to show the UITableViewController in the position marked "here" just above the bottom bar.

I'm new to iOS and I'm banging my head against a wall because of this.

Thanks in advance!

A UITableViewController expects to use the entire screen. I don't think it's what you want here.

I'd just create a UIView subclass and add a UITableView to it. You can then add your custom view to the current view as a subview. Your subclass can be the data source and delegate, so it can be completely self-contained so you can use it anywhere in the app. It can also be full-screen sized if you want to detect tapping outside of the table view to dismiss the custom view. Just make the backgroundColor clearColor and add a gesture recognizer to detect the tap.

I think that you may have some better options for this than using an UITableViewController but nevertheless here goes:

You basically want to add a child view controller. It can be done like this (this will be in Swift but I can add an ObjC version too):

func buttonTap(sender: UIButton) {
    let viewController = UITableViewController(style: .Plain)
    viewController.willMoveToParentViewController(self)

    self.addChildViewController(viewController)
    viewController.view.frame = CGRectMake(0, 0, self.view.bounds.width, self.view.bounds.height * 0.5)
    self.view.addSubview(viewController.view)

    viewController.didMoveToParentViewController(self)
}

This is called creating a container view controller and is quite common ( UIPageViewController , UINavigationController , ... all use this mechanism).

However since I don't really like UITableViewControllers I would recommend creating a simple UITableView and adding it as a subview. As for the delegate and dataSource both can be separated into separate classes (and files) so you can avoid a bloated implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM