Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Add InputAccessoryView in Swift for UITextField and UITextView

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 6.78k
    Comment on it

    Hi,

     

    Sometimes we need to show our custom accessory view when UITextField/UITextView is in editing mode or being edited. We can use inputAccessoryView property to assign a view just above the system keyboard.
    Input accessory view is very helpful when you are dealing with UITextView. Because when you press return key it actually starts a new line and user can’t end editing from the UITextView. But with the help of inputAccessory view you can overcome such problems with ease.
    Here I’m going to tell you how you can add a toolbar as custom accessory view for UITextField or UITextView in swift.

     

    1- Create an instance of toolbar with with it’s frame.

    let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 44))

    2- Now we are going to add a UIBarButtonItem to above created toolbar.

    let doneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.doneButtonTapped(button:)))

    You can see that the selector is doneButtonTapped for ‘doneButton’, so make sure that it’s presented in the class somewhere.

    func doneButtonTapped(button:UIBarButtonItem) -> Void {
        // do you stuff here..
    }

    3- Add above created button as items to toolbar(created in #1).

    toolBar.items = [doneButton]

    this is how we are adding items to tool bar. You can also use an alternate method to have animation in your code.

    toolBar.setItems([doneButton], animated: true)

    4- Use UITextField’s property ‘inputAccessoryView’ to assign/add inputAccessoryView.

    textField.inputAccessoryView = toolBar

    5- Now run your app and start editing the fields, you’ll see that a input accessory view is present with system keyboard.

     

    Code Snippet:

    func addAccessoryView() -> Void {
        let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 44))
        let doneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.doneButtonTapped(button:)))
        toolBar.items = [doneButton]
        toolBar.tintColor = UIColor.red
        textField.inputAccessoryView = toolBar
    }
    
    func doneButtonTapped(button:UIBarButtonItem) -> Void {       
         // do you stuff with done here
    }

     

     

    Thank you

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: