David Sanford David Sanford - 1 year ago 75
iOS Question

Adding Done button to number pad within UITableViewCell

I am using dynamic cells within a UITableview and am trying to create a done button that will display with the numberpad within a UITableViewCell.

I have the code to accomplish this within a ViewController for other fields, but this does not work when the field in within a UITableViewCell.

IBOulet is here:

class StartingTankUsageCell: UITableViewCell, UITextFieldDelegate

@IBOutlet var startingPressureTextField: UITextField!

I have set up in my ViewController:

import UIKit

class DiveDetailsViewController: UITableViewController, LocationDelegate, ItemDataSelectedProtocol

override func viewDidLoad()

// DONE button on NumberPad for StartingPressure
func addDoneButtonOnKeyboardStartingPressure()
let doneToolbar: UIToolbar = UIToolbar(frame: CGRectMake(0, 0, 320, 50))
doneToolbar.barStyle = UIBarStyle.Default

let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: #selector(DiveDetailsViewController.addDoneButtonOnKeyboardStartingPressure))

var items = [UIBarButtonItem]()

doneToolbar.items = items

self.startingPressureTextField.inputAccessoryView = doneToolbar

func doneButtonActionDuration()
} // finish DONE button on NumberPad for StartingPressure

The error I am getting is "Value to type 'DiveDetailsViewController' has no member 'startingPressureTextField'"

Can someone please help me either the allow the vc to see the UITextField in the UITableViewCell or help me with a done button that can reside within the UITableViewCell.

enter image description here

Answer Source

You can make an extension for UITextField like this:

extension UITextField {

    public override func awakeFromNib() {

    func addHideinputAccessoryView() {

        let button = UIButton(frame: CGRect(x: 0,y: 0,width: 50,height: 44))
        button.setTitle("Done", forState: .Normal)
        button.setTitleColor(UIColor.blueColor(), forState: .Normal)
        button.setTitleColor(UIColor.lightGrayColor(), forState: .Highlighted)
        button.titleLabel?.font = UIFont.systemFontOfSize(14)
        button.addTarget(self, action: #selector(self.resignFirstResponder), forControlEvents: .TouchUpInside)

        let barButton = UIBarButtonItem(customView: button)
        let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil)
        let toolbar = UIToolbar(frame: CGRectMake(0, 0, self.frame.size.width, 44))

        toolbar.items = [space, barButton]
        self.inputAccessoryView = toolbar