【问题标题】:Connect UIView with XIB to another ViewController将带有 XIB 的 UIView 连接到另一个 ViewController
【发布时间】:2017-05-19 07:58:52
【问题描述】:

我有一个 UIView,我将在其中为按钮编写操作。在 XIB 文件中,我在键盘上方有一个带有这些按钮的栏。如何将这些按钮连接到具有 UITextView 的 ViewController 以及单击按钮时的操作应在 UITextView 中完成(例如:当我单击“粗体”按钮时,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)
}

【问题讨论】:

    标签: ios swift2 swift3 xib bold


    【解决方案1】:

    如何将这些按钮连接到具有 UITextView 的 ViewController

    在加载条时,视图控制器在 .xib 文件中有对条的引用。因此它引用了按钮。因此它可以调用addTarget(_:action:for:)来配置按钮动作来调用视图控制器的一个方法,从而可以将文本视图中的文本加粗。

    【讨论】:

    • 我不知道在哪里调用“addTarget(_:action:for:)”。我用 .xib 文件中的按钮制作了这个栏
    • 你还没有展示你如何加载你谈到的 .xib 的代码,所以除了我所说的之外,我无法告诉你:在你加载它的时候,你有你需要的参考。你展示了一个完全没有意义的屏幕截图。代码才是最重要的。
    • 哈哈哈我知道了,我想展示按钮,这里是代码
    • 不显示代码的屏幕截图。不要显示代码图片。显示代码。复制并粘贴。
    • 好。因此,就在您设置textBody.inputAccessoryView 的位置,这是一个包含按钮的视图。如果你想在 .xib 文件中给每个按钮一个不同的标签,你可以使用viewWithTag 依次找到每个按钮并为其分配一个动作目标对,正如我在我的回答。
    猜你喜欢
    • 2012-03-28
    • 2023-03-05
    • 2023-03-21
    • 2017-10-28
    • 1970-01-01
    • 2013-03-02
    • 2013-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多