【问题标题】:iOS - Cannot access UITextView delegate inside a UITableViewCell classiOS - 无法访问 UITableViewCell 类中的 UITextView 委托
【发布时间】:2017-02-12 23:30:17
【问题描述】:

我在尝试访问实例化的UITableViewCell 类中的UITableViewDelegate 方法时发现了一些问题。

我正在尝试访问 func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {} 并且函数不会触发,我想这是因为我在尝试设置委托时遇到了一些问题。

代码如下:

import UIKit
class TableViewCell: UITableViewCell, UITextViewDelegate {

    @IBOutlet var titleLabel: UILabel!
    @IBOutlet var textView: UITextView!
    @IBOutlet var postImageView: UIImageView!


    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
        print("link tapped")
        return true
    }

    init() {
        super.init()
        textView.delegate = self
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }
}

super.init() 行显示此错误

TableViewCell.swift - "必须调用超类的指定初始化程序" 'UITableViewCell'

关于如何克服这个问题的任何提示?

提前致谢

最终编辑 我已经做了我真正想做的事。 我没有在 UITableViewCell 类中使用 UITextFieldDelegate ,而是将 UITextFieldDelegate 添加到使用单元格本身的 ViewController 中,并且在单元格配置上做了: cell.textView.degelate = Self ,然后我实现了委托功能 func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {}

感谢孩子们的回答。

【问题讨论】:

  • 我已经尝试过方便的 init() 并且它不起作用
  • 我不认为 super.init() 是指定的初始化程序。尝试其他之一。我认为可能有一个 super.init(nib:, bundle:) 或类似的东西。
  • 如果我尝试 super.init(style: UITableViewCellStyle.default, reuseIdentifier: "mainCell") 初始化程序,则会显示所需的 init() 致命错误。
  • 在表格视图单元格中访问对象委托属性应该不难,我错过了一些我看不到的东西:/

标签: ios uitableview swift3 uitextviewdelegate


【解决方案1】:
override func awakeFromNib() {
    super.awakeFromNib()
    textView.delegate = self
}

干得漂亮

【讨论】:

  • 欢迎来到 StackOverflow!虽然答案总是很受欢迎,但请提供一些围绕您的答案的背景信息,并查看help article 以获取有关如何撰写出色答案的信息。
  • 奇怪的是,这行得通,但我发誓我以前试过这个,但编译时出错:/ 还是谢谢你 m8
【解决方案2】:

给你带来麻烦的不是textView.delegate = self,而是super.init()。您需要使用 nibName 和 bundle 正确调用它。

init() {
    super.init(nibName: PutTheStringHere, bundle: PutTheBundleHere)
    textView.delegate = self
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多