UITableView sticky footer / custom toolbar impleme

2020-05-01 09:09发布

问题:

I am using a UITableViewController, and what I would like to do is to add a custom toolbar under the UIView.

I have tried enabling the toolbar of the navigationController (code below) but it won't seem to work properly. UITextField won't call delegates, and key presses of the text field are not shown in the textfield itself.

Using a toolbar like this is not my first choice, I would like to have my custom view under my UITableViewController where I can put my items, which acts like a UIToolbar. (stays as a UIView footer)

Code:

    self.navigationController.toolbarHidden = NO;
    // create toolbar objects
    UITextField *inputField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 230, 31)];
    inputField.backgroundColor = [UIColor clearColor];
    inputField.borderStyle = UITextBorderStyleRoundedRect;
    inputField.inputAccessoryView = self.navigationController.toolbar;
    inputField.returnKeyType = UIReturnKeyDone;
    inputField.delegate = self;


    UIButton *sendButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
    sendButton.titleLabel.text = @"Send";
    sendButton.backgroundColor = [UIColor greenColor];

    // add objects into navigation controller
    self.toolbarItems = [NSArray arrayWithObjects:
                         [[UIBarButtonItem alloc] initWithCustomView:inputField],
                         [[UIBarButtonItem alloc] initWithCustomView:sendButton], nil];

回答1:

Instead of subclassing UITableViewController for your implementation, you might find it easier to subclass a plain UIViewController and add a UITableView to it. This would give you more flexibility in terms of customizing the layout.

Basically the steps would be:

  1. Have your class inherit from UIViewController (instead of UITableViewController)
  2. Have your class implement the UITableViewDelegate and UITableViewDataSource protocols
  3. Implement the UITableViewDelegate and UITableViewDataSource methods in your class (e.g. cellForRowAtIndexPath:, didSelectRowAtIndexPath:, etc)
  4. In IB, add a UITableView as a subview to your view controller's view
  5. Set the delegate and datasource properties of the table view you just added to be your viewcontroller class
  6. Resize the frame of the UITableView to allow space at the bottom for your inputField and button

This way you can add the inputField and button to your viewController's view (at the bottom) and they won't scroll because they are separate from the tableview.