我有一个UIView,我将在哪里写按钮的动作。在XIB文件中,我喜欢使用这些按钮在键盘上方的条形图。如何将这些按钮连接到具有UITextView的ViewController以及单击按钮时应该在UITextView中完成操作(例如:当我单击" Bold"按钮时,UITextView中的选定文本应该是粗体) [![在此处输入图像说明] [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)
}
答案 0 :(得分:1)
如何将这些按钮连接到具有UITextView
的ViewController
视图控制器在加载栏时引用 .xib 文件中的栏。因此它引用了按钮。因此,它可以调用addTarget(_:action:for:)
来配置按钮操作以调用视图控制器的方法,这反过来可以在文本视图中加粗文本。