Swift3 TextViewにToolBarを追加する方法

  • 5
    Like
  • 0
    Comment

no.gif


    func keyboardToolbar(textView: UITextView) {

        let toolbar: UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
        toolbar.barStyle = UIBarStyle.default
        toolbar.bounds.size.height = 28

        let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)


        let done: UIBarButtonItem = UIBarButtonItem(title: "done", style: UIBarButtonItemStyle.done, target: self, action: #selector(self.doneButtonActionn))
        done.tintColor = UIColor.red

        let clear: UIBarButtonItem = UIBarButtonItem(title: "Clear", style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.doneButtonAction))
        clear.tintColor = UIColor.black


        var items = [UIBarButtonItem]()

        items.append(clear)
        items.append(flexSpace)

        items.append(done)

        toolbar.items = items
        toolbar.sizeToFit()

        textView.inputAccessoryView = toolbar


    }


    func doneButtonAction() {

        self.bodyTextView.resignFirstResponder()
        //self.bottomSpace.constant = 12
    }

    func doneButtonActionn() {

        self.bodyTextView.resignFirstResponder()
        //self.bottomSpace.constant = 12
    }

    func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {

        self.keyboardToolbar(textView: textView)
        return true
    }