Он отлично работает с клавиатурой по умолчанию, но я не могу заставить ее работать с numpad.
Любые идеи?
Он отлично работает с клавиатурой по умолчанию, но я не могу заставить ее работать с numpad.
Любые идеи?
Насколько я знаю, вы не можете добавить кнопку Готово на клавиатуре; Вы должны были бы добавить inputAccessoryView
к UITextField
или UITextView
(если это то, что вы используете).
Проверьте документацию для получения дополнительной информации.
Изменить: проверьте этот вопрос для примера о том, как это сделать.
Редактировать 2: Подобный пример в Swift.
Редактировать 3: код из редактирования 2, так как срок действия ссылки может истечь.
override func viewDidLoad()
{
super.viewDidLoad()
//--- add UIToolBar on keyboard and Done button on UIToolBar ---//
self.addDoneButtonOnKeyboard()
}
//--- *** ---//
func addDoneButtonOnKeyboard()
{
var doneToolbar: UIToolbar = UIToolbar(frame: CGRectMake(0, 0, 320, 50))
doneToolbar.barStyle = UIBarStyle.BlackTranslucent
var flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
var done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: Selector("doneButtonAction"))
var items = NSMutableArray()
items.addObject(flexSpace)
items.addObject(done)
doneToolbar.items = items
doneToolbar.sizeToFit()
self.textView.inputAccessoryView = doneToolbar
self.textField.inputAccessoryView = doneToolbar
}
func doneButtonAction()
{
self.textViewDescription.resignFirstResponder()
}
Swift 4.2
func addDoneButtonOnKeyboard(){
let doneToolbar: UIToolbar = UIToolbar(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
doneToolbar.barStyle = .default
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.doneButtonAction))
let items = [flexSpace, done]
doneToolbar.items = items
doneToolbar.sizeToFit()
txtMobileNumber.inputAccessoryView = doneToolbar
}
@objc func doneButtonAction(){
txtMobileNumber.resignFirstResponder()
}
версия Swift-3 (от решения Марко, которая работала для меня)
(в моем случае у меня есть UITextField, обозначенный как textfield
)
func addDoneButtonOnKeyboard() {
let doneToolbar: UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 320, height: 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(ViewController.doneButtonAction))
var items = [UIBarButtonItem]()
items.append(flexSpace)
items.append(done)
doneToolbar.items = items
doneToolbar.sizeToFit()
self.textfield.inputAccessoryView = doneToolbar
}
func doneButtonAction() {
self.textfield.resignFirstResponder()
}
Swift 3 с использованием @IBInpectable
и расширения. Выпадающий список появится под инспектором атрибутов в построителе интерфейса для каждого UITextField в проекте.
extension UITextField{
@IBInspectable var doneAccessory: Bool{
get{
return self.doneAccessory
}
set (hasDone) {
if hasDone{
addDoneButtonOnKeyboard()
}
}
}
func addDoneButtonOnKeyboard()
{
let doneToolbar: UIToolbar = UIToolbar(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
doneToolbar.barStyle = .default
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.doneButtonAction))
let items = [flexSpace, done]
doneToolbar.items = items
doneToolbar.sizeToFit()
self.inputAccessoryView = doneToolbar
}
func doneButtonAction()
{
self.resignFirstResponder()
}
}
Вы можете добавить панель инструментов с кнопкой "Готово" к клавиатуре. InputAccessoryView
свойство текстового поля можно использовать для установки этой панели инструментов.
Ниже приведен код, который Ive использовал в моем случае
//Add done button to numeric pad keyboard
let toolbarDone = UIToolbar.init()
toolbarDone.sizeToFit()
let barBtnDone = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.Done,
target: self, action: #selector(VerifyCardViewController.doneButton_Clicked(_:)))
toolbarDone.items = [barBtnDone] // You can even add cancel button too
txtCardDetails3.inputAccessoryView = toolbarDone
Если ваша кнопка Done
должна просто закрыть цифровую панель, то самой простой версией будет вызов resignFirstResponder
в качестве селектора, например:
UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: textField, action: #selector(UITextField.resignFirstResponder))
Этот код работает в iOS9 и Swift 2, я использую его в своем приложении:
func addDoneButtonOnNumpad(textField: UITextField) {
let keypadToolbar: UIToolbar = UIToolbar()
// add a done button to the numberpad
keypadToolbar.items=[
UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: textField, action: #selector(UITextField.resignFirstResponder)),
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil)
]
keypadToolbar.sizeToFit()
// add a toolbar with a done button above the number pad
textField.inputAccessoryView = keypadToolbar
}
Прежде всего позвольте мне сказать вам одну вещь, которую вы можете добавить на кнопку "Готово" на своем клавиатуре по умолчанию. Фактически сегодня я только что преодолел эту проблему и решил. Готовый код, просто поместите это в свой класс .swift. Я использую Xcode 7 и тестирую это с помощью iPad Retina (ios 9).
В любом случае, больше не говорите здесь код.
//Creating an outlet for the textfield
@IBOutlet weak var outletTextFieldTime: UITextField!
//Adding the protocol of UITextFieldDelegate
class ReservationClass: UIViewController, UITextFieldDelegate {
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
//Making A toolbar
let keyboardDoneButtonShow = UIToolbar(frame: CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height/17))
//Setting the style for the toolbar
keyboardDoneButtonShow.barStyle = UIBarStyle .BlackTranslucent
//Making the done button and calling the textFieldShouldReturn native method for hidding the keyboard.
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: Selector("textFieldShouldReturn:"))
//Calculating the flexible Space.
let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
//Setting the color of the button.
item.tintColor = UIColor .yellowColor()
//Making an object using the button and space for the toolbar
let toolbarButton = [flexSpace,doneButton]
//Adding the object for toolbar to the toolbar itself
keyboardDoneButtonShow.setItems(toolbarButton, animated: false)
//Now adding the complete thing against the desired textfield
outletTextFieldTime.inputAccessoryView = keyboardDoneButtonShow
return true
}
//Function for hidding the keyboard.
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
}
Что дает мне решение как...
Еще одна вещь, которую я просто хочу сказать вам, что это рабочее решение, которое я использовал в своем недавнем проекте. Я опубликовал это, потому что для этой проблемы не существует рабочего решения. Рабочий код и объяснение, как и обещалось.
РЕДАКТИРОВАТЬ: -
Сделайте его более профессиональным... Если вы следуете приведенному выше коду, тогда он также даст вам рабочее решение, но здесь я пытаюсь сделать его более профессиональным. Обратите внимание на код MOD. Я оставил предыдущий неиспользуемый код с цитатой.
Изменения..
Позиционирование пользовательской кнопки в левой части экрана с помощью FlexSpace и NegativeSpace.
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
let keyboardDoneButtonShow = UIToolbar(frame: CGRectMake(200,200, self.view.frame.size.width,30))
// self.view.frame.size.height/17
keyboardDoneButtonShow.barStyle = UIBarStyle .BlackTranslucent
let button: UIButton = UIButton()
button.frame = CGRectMake(0, 0, 65, 20)
button.setTitle("Done", forState: UIControlState .Normal)
button.addTarget(self, action: Selector("textFieldShouldReturn:"), forControlEvents: UIControlEvents .TouchUpInside)
button.backgroundColor = UIColor .clearColor()
// let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: Selector("textFieldShouldReturn:"))
let doneButton: UIBarButtonItem = UIBarButtonItem()
doneButton.customView = button
let negativeSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil)
negativeSpace.width = -10.0
let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
//doneButton.tintColor = UIColor .yellowColor()
let toolbarButton = [flexSpace,doneButton,negativeSpace]
keyboardDoneButtonShow.setItems(toolbarButton, animated: false)
outletTextFieldTime.inputAccessoryView = keyboardDoneButtonShow
return true
}
Теперь он дает мне следующее... Кроме того, попробуйте сопоставить фотографии и найти изменения.
Спасибо.
Надеюсь, это помогло. Извините за длинный ответ.
По словам Марко Николовского, ответьте
Вот objective-C ответ:
- (void)ViewDidLoad {
[self addDoneButtonOnKeyboard];
}
- (void)addDoneButtonOnKeyboard {
UIToolbar *toolBarbutton = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
toolBarbutton.barStyle = UIBarStyleBlackTranslucent;
UIBarButtonItem *barBtnItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(doneButtonAction)];
NSMutableArray *items = [[NSMutableArray alloc] init];
[items addObject:barBtnItem];
[items addObject:done];
toolBarbutton.items = items;
[toolBarbutton sizeToFit];
self.timeoutTextField.inputAccessoryView = toolBarbutton;
}
- (void)doneButtonAction {
[self.view endEditing:YES];
}
Вы можете создать собственный класс. Я использую Swift 4:
class UITextFieldWithDoneButton: UITextField {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.addDoneButtonOnKeyboard()
}
fileprivate func addDoneButtonOnKeyboard() {
let doneToolbar: UIToolbar = UIToolbar(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
doneToolbar.barStyle = .default
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.doneButtonAction))
let items = [flexSpace, done]
doneToolbar.items = items
doneToolbar.sizeToFit()
self.inputAccessoryView = doneToolbar
}
@objc fileprivate func doneButtonAction() {
self.resignFirstResponder()
}
}