ios - 如何从主类访问自定义 Collection View 单元格类中的 TextView

标签 ios swift uicollectionview uitextview

我的每个 Collection View 单元格中都有两个 TextView ,我为这些单元格创建了一个自定义类。这是代码:

class CustomWriterPageCell: UICollectionViewCell {

    fileprivate let textViewOne: UITextView = {

        let tv = UITextView()
        tv.backgroundColor = .cyan
        tv.text = "Chapter Title"
        tv.font = UIFont(name: "Avenir-Roman", size: 27)
        tv.textColor = .gray
        return tv

    }()

    fileprivate let textViewTwo: UITextView = {

        let tv = UITextView()
        tv.textColor = .gray
        tv.text = "Start your story..."
        tv.textContainerInset = UIEdgeInsets(top: 20, left: 15, bottom: 20, right: 15)
        tv.font = UIFont(name: "Avenir-Book", size: 23)
        tv.backgroundColor = .black
        return tv

    }()
}

我想为这两个 TextView 添加占位符,但问题是,由于它们在自定义类中,据我所知,无法找出正在编辑的 TextView ,所以我不能在 textViewDidEndEditing 发生时添加相应的占位符,有没有办法找出正在编辑的 TextView ?有没有办法从主类访问 TextView ?

最佳答案

在您的 CustomWriterPageCell 类中:

fileprivate let textViewOne: UITextView = {

    let tv = UITextView()
    tv.backgroundColor = .cyan
    tv.text = "Chapter Title"
    tv.font = UIFont(name: "Avenir-Roman", size: 27)
    tv.textColor = .gray
    return tv

}()

fileprivate let textViewTwo: UITextView = {

    let tv = UITextView()
    tv.textColor = .gray
    tv.text = "Start your story..."
    tv.textContainerInset = UIEdgeInsets(top: 20, left: 15, bottom: 20, right: 15)
    tv.font = UIFont(name: "Avenir-Book", size: 23)
    tv.backgroundColor = .black
    return tv

}()

override init(frame: CGRect) {
    super.init(frame: frame)

    textViewOne.delegate = self
    textViewTwo.delegate = self

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

然后:

extension CustomWriterPageCell : UITextViewDelegate {
      func textViewDidEndEditing(_ textView: UITextView) {

              if textView == textViewOne {
                  textView.text = "..."
              }
              else if textView == textViewTwo {
                  textView.text = "..."
              }
      }
}

这样,您的 View Controller 仍然不需要知道您的 TextView 。

关于ios - 如何从主类访问自定义 Collection View 单元格类中的 TextView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57977396/

相关文章:

ios - 如何在分页 UIScrollView 中显示确定的项目而不是仅从 0 加载它

ios - 在 UICollectionViewCell 中将 CAGradientLayer 添加到 UIImageView 有奇怪的行为

iphone - 为什么对主队列的 dispatch_sync( ) 调用会阻塞主队列?

swift - 调用 SwiftyDropbox 方法时的 NSURLErrorDomain 代码 -999

ios - 在 Controller 之间传递数据 - 在展开 Optional 时意外发现 nil

ios - 仅限 iOS9 上的 UICollectionView NSInternalInconsistencyException 错误

ios - CoreAudio 的首选语言

iphone - SQLite ANALYZE 破坏索引

ios - Swift - NSKeyedUnarchiver unarchiveObjectWithData 在 NSMutableArray

swift - 带有 switch swift 的通用枚举