我在UITableview中使用动态单元格,并尝试创建一个完成按钮,该按钮将在UITableViewCell 中显示数字键盘。
我有一个代码可以在ViewController中为其他字段完成此操作,但是当UITableViewCell中的字段时,这不起作用。
IBOulet在这里:
class StartingTankUsageCell: UITableViewCell, UITextFieldDelegate
{
@IBOutlet var startingPressureTextField: UITextField!
我在ViewController中设置了:
import UIKit
class DiveDetailsViewController: UITableViewController, LocationDelegate, ItemDataSelectedProtocol
{
override func viewDidLoad()
{
super.viewDidLoad()
self.addDoneButtonOnKeyboardStartingPressure()
}
// 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]()
items.append(flexSpace)
items.append(done)
doneToolbar.items = items
doneToolbar.sizeToFit()
self.startingPressureTextField.inputAccessoryView = doneToolbar
}
func doneButtonActionDuration()
{
self.startingPressureTextField.resignFirstResponder()
} // finish DONE button on NumberPad for StartingPressure
我得到的错误是"Value to type 'DiveDetailsViewController' has no member 'startingPressureTextField'"
有人可以请帮助我允许vc在UITableViewCell中查看UITextField,或者帮助我使用可以驻留在UITableViewCell中的完成按钮。
答案 0 :(得分:5)
您可以像这样为UITextField制作扩展名:
extension UITextField {
public override func awakeFromNib() {
super.awakeFromNib()
self.addHideinputAccessoryView()
}
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
}
}
答案 1 :(得分:2)
你也可以这样试试,简化一下代码:
import UIKit
import Foundation
extension UITextField {
func addHideinputAccessoryView() {
let toolbar = UIToolbar()
toolbar.sizeToFit()
let item = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done,
target: self, action: #selector(self.resignFirstResponder))
toolbar.setItems([item], animated: true)
self.inputAccessoryView = toolbar
}
}