Connect UIView with XIB to another ViewController

194 views Asked by At

I have a UIView where will i write actions for buttons. In XIB file I have like a bar that is above the keyboard with those buttons. How to connect these buttons to ViewController that has UITextView and when button is clicked action should be done in UITextView (example: When i click the "Bold" button, selected text in UITextView should be bold) enter image description here [![enter image description here][2]][2]

import UIKit

protocol NoteViewDelegate {

    func didUpdateNoteWithTitle(newTitle : String, andBody newBody : String)
}

class NewNoteViewController: UIViewController , UITextViewDelegate {

    var delegate : NoteViewDelegate?


    @IBOutlet weak var textBody: UITextView!

    var strBodyText : String!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.textBody.text = self.strBodyText

        self.textBody.becomeFirstResponder()

        self.textBody.delegate = self

        NotificationCenter.default.addObserver(self, selector: #selector(NewNoteViewController.updateTextView(notification:)) , name: Notification.Name.UIKeyboardWillChangeFrame, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(NewNoteViewController.updateTextView(notification:)) , name: Notification.Name.UIKeyboardWillHide, object: nil)

        textBody.inputAccessoryView = Bundle.main.loadNibNamed("CustomAccessoryView", owner: self, options: nil)?.first as? UIView
}

    func updateTextView (notification:Notification) {
        let userInfo = notification.userInfo!

        let keyboardEndFrameScreenCoordinates = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let keyboardEndFrame = self.view.convert(keyboardEndFrameScreenCoordinates, to: view.window)

        if notification.name == Notification.Name.UIKeyboardWillHide {
            textBody.contentInset = UIEdgeInsets.zero

        }else{
            textBody.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardEndFrame.height, right: 0)

            textBody.scrollIndicatorInsets = textBody.contentInset
    }
        textBody.scrollRangeToVisible(textBody.selectedRange)
}
1

There are 1 answers

5
matt On

How to connect these buttons to ViewController that has UITextView

The view controller has a reference to the bar in the .xib file at the time the bar is loaded. Therefore it has references to the buttons. Therefore it can call addTarget(_:action:for:) to configure the button actions to call a method of the view controller, which in turn can boldify the text in the text view.