Làm cách nào để thêm nút “Xong” vào Numpad trong iOS bằng Swift?


79

Nó hoạt động tốt với bàn phím mặc định, nhưng tôi không thể làm cho nó hoạt động với numpad.

Có ý kiến ​​gì không?



2
Tôi không quan tâm đến việc tạo bàn phím mới, tôi chỉ muốn thêm một nút vào UIToolBar, sau đó thêm nó vào textField dưới dạng inputAccessoryView, như đây: stackoverflow.com/a/11382044/3207979 , nhưng tôi chưa tìm ra nó chưa, làm thế nào để làm điều đó nhanh chóng ..
Dejan Skledar

Thay vì Bàn phím hoặc Thanh công cụ tùy chỉnh, chúng ta có thể đạt được điều này bằng cách thêm nút tùy chỉnh vào bàn phím mặc định. Tham khảo câu trả lời này .
Nazik

Đối với giải pháp sử dụng kịch bản https://stackoverflow.com/a/37896351/1465582
Irshad Mohamed

Câu trả lời:


100

Theo như tôi biết, bạn không thể thêm nút Xong trên phần bàn phím; bạn đã thêm một inputAccessoryViewvào UITextFieldhoặc UITextView(nếu đó là những gì bạn đang sử dụng).

Kiểm tra tài liệu để biết thêm thông tin .

Chỉnh sửa : Kiểm tra câu hỏi này để biết ví dụ về cách thực hiện điều đó.

Chỉnh sửa 2 : Ví dụ tương tự trong Swift .

Chỉnh sửa 3 : Mã từ chỉnh sửa 2, vì liên kết có thể hết hạn.

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()
    }

Hoạt động hoàn hảo. Thực hiện nhanh chóng và dễ dàng. Cảm ơn!
Octavio Antonio Cedeño

3
Bạn có thể thay đổi điều này và bạn wont phải bản địa hoá nút: hãy thực hiện: UIBarButtonItem = UIBarButtonItem (barButtonSystemItem: UIBarButtonSystemItem.done, mục tiêu: tự, hành động: #selector (self.doneButtonAction))
Zeezer

59

Phiên bản Swift-3 ( giải pháp của Marko - phù hợp với tôi )

( trong trường hợp của tôi, tôi có một UITextField được xác định là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()
}

48

Giải pháp Swift 5 sử dụng @IBInpectablevà phần mở rộng. Một danh sách thả xuống sẽ xuất hiện bên dưới Trình kiểm tra thuộc tính trong Trình tạo giao diện cho mọi UITextField trong dự án.

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
    }

    @objc func doneButtonAction()
    {
        self.resignFirstResponder()
    }
}

3
Câu trả lời tuyệt vời. Tôi hy vọng mọi người đang cuộn xuống đây.
biomiker

15

Bạn có thể thêm thanh công cụ với nút Xong vào bàn phím. InputAccessoryViewthuộc tính của textfield có thể được sử dụng để thiết lập thanh công cụ này.

Dưới đây là mã mà tôi đã sử dụng trong trường hợp của mình

//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

Ảnh chụp màn hình


5

Nếu Donenút của bạn được cho là chỉ đóng bàn phím số, thì phiên bản đơn giản nhất sẽ được gọi resignFirstResponderdưới dạng bộ chọn như sau:

UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: textField, action: #selector(UITextField.resignFirstResponder))

Mã này hoạt động trong iOS9 và Swift 2, tôi đang sử dụng nó trong ứng dụng của mình:

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
}

4

Giải pháp đơn giản nhất mà tôi có thể tìm thấy - hoạt động với Swift 4.2 - hy vọng điều này sẽ giúp :)

extension UITextField {

   func addDoneButtonOnKeyboard() {
       let keyboardToolbar = UIToolbar()
       keyboardToolbar.sizeToFit()
       let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace,
           target: nil, action: nil)
       let doneButton = UIBarButtonItem(barButtonSystemItem: .done,
           target: self, action: #selector(resignFirstResponder))
       keyboardToolbar.items = [flexibleSpace, doneButton]
       self.inputAccessoryView = keyboardToolbar
   }
}

Sau đó, bạn có thể xử lý hành động đã thực hiện trong textFieldDidEndEditingphương thức ủy quyền hoặc chỉ cần thêm một phương thức tùy chỉnh vào tiện ích mở rộng và đặt nó trong bộ chọn của doneButton.


Giải pháp tuyệt vời, đơn giản và thanh lịch!
MrMins

3

Trước hết, hãy để tôi nói với bạn một điều rằng Bạn có thể THÊM một nút Xong trên KeyBoard mặc định của mình. Thực ra hôm nay mình mới xem qua vấn đề này và giải quyết. Mã đã tạo sẵn sàng, chỉ cần đặt mã này vào lớp .swift của bạn. Tôi đang sử dụng Xcode 7 và thử nghiệm điều này bằng iPad Retina (ios 9).

Dù sao không nói nhiều ở đây là mã.

  //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
   }
}

Đó là cho tôi giải pháp là ...

nhập mô tả hình ảnh ở đây

Một điều nữa tôi chỉ muốn nói với bạn rằng đây là giải pháp hiệu quả mà tôi đã sử dụng trong dự án gần đây của mình. Tôi đã đăng bài này vì không có giải pháp làm việc nào cho vấn đề này. Mã làm việc và giải thích như đã hứa.

BIÊN TẬP :-

Làm cho nó chuyên nghiệp hơn ... Nếu bạn đang làm theo đoạn mã trên thì nó cũng sẽ cung cấp cho bạn giải pháp làm việc nhưng ở đây tôi đang cố gắng làm cho nó trở nên Chuyên nghiệp hơn. Vui lòng thông báo MOD mã. Tôi để lại mã không sử dụng trước đó với báo giá.

Các thay đổi ..

  1. Tạo một đối tượng Nút riêng lẻ
  2. Đặt nó vào thanh công cụ
  3. Giảm kích thước của thanh công cụ đã được tạo trước đó
  4. Định vị nút tùy chỉnh ở bên trái màn hình bằng FlexSpace và 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
    }
    

Nó bây giờ mang lại cho tôi những điều sau đây ... Hơn nữa, hãy cố gắng ghép các bức tranh và tìm những thay đổi.

nhập mô tả hình ảnh ở đây

Cảm ơn.

Hy vọng điều này sẽ giúp. Xin lỗi vì câu trả lời dài.


3

Bởi vì các câu trả lời trên là cũ trong Xcode 11 trở lên, công cụ ban đầuBar like UIToolbar()sẽ ném một giới hạn phá vỡ trên bảng điều khiển mỗi khi bạn chạy như ở đây, vì vậy hãy sử dụng UIToolbar(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 35)) thay thế

Mã mẫu

            let toolBar =  UIToolbar(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 35))
            toolBar.barStyle = .default
            toolBar.sizeToFit()

            // Adding Button ToolBar
            let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(doneButtonTapped))
            toolBar.items = [doneButton]
            toolBar.isUserInteractionEnabled = true
            textField.inputAccessoryView = toolBar

Điều này hoạt động, nhưng làm thế nào bạn đưa ra khung 35?
geohei

1
Tôi nghĩ rằng đó là chiều cao mặc định có thể bạn có thể cấu hình nó để thay đổi
SuryaKantSharma

Bạn có thể đặt bất kỳ số nào (đã thử từ 0 đến 999). Có vẻ như điều này dường như không thay đổi được gì.
geohei

2

Theo Marko Nikolovski trả lời

Đây là câu trả lời khách quan-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];
}

2

Bạn có thể tạo một lớp tùy chỉnh. Tôi đang sử dụng 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()
    }
}

1
Điều này làm một điều trị cho tôi. Chỉ cần sao chép và dán vào cuối tệp .swift, sau đó sử dụng: textfieldOutput.addDoneButtonOnKeyboard () vào ViewDidLoad. Cảm ơn bạn!
David_2877

2

Tôi sẽ sử dụng thư viện gọi IQKeyboardManagerSwift .

Bạn phải chèn một dòng mã vào phương thức didFinishWithLaunching của AppDelegates và nó áp dụng tất cả các tính năng cần thiết cho tất cả các Trường văn bản.

import IQKeyboardManagerSwift

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    //Following line is all you need and it applies for all TextFields
    IQKeyboardManager.shared.enable = true
    return true
}

0

cách đơn giản và dễ dàng để thêm nút "XONG" trên bất kỳ bàn phím nào là thêm thư viện chung

IQKeyboardManager

thêm mã bên dưới trong appdelegate tại ứng dụng (_ ứng dụng: UIApplication, didFinishLaunchingWithOptions.

IQKeyboardManager.shared.enable = true
IQKeyboardManager.shared.enableAutoToolbar = true
IQKeyboardManager.shared.keyboardDistanceFromTextField = 15
IQKeyboardManager.shared.shouldResignOnTouchOutside = true
Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.