如何从主类访问自定义集合视图单元格类中的文本视图 [英] How to access text views in custom collection view cell class from the main class

查看:22
本文介绍了如何从主类访问自定义集合视图单元格类中的文本视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的每个集合视图单元格中有两个文本视图,我为这些单元格创建了一个自定义类.这是代码:

I've got two text views in each of my collection view cells, I've made a custom class for the cells. here is the code:

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

    }()
}

我想为这两个文本视图添加占位符,但问题是由于它们在自定义类中,我知道无法找出正在编辑的文本视图,因此我无法在 textViewDidEndEditing 发生时添加相应的占位符,有没有办法找出正在编辑哪个文本视图?有没有办法从主类访问文本视图?

I would like to add placeholders to both these text views but the problem is that since they are in a custom class there is no way, that I know of, to find out which text view is being edited so I can't add the respective placeholders back when textViewDidEndEditing takes place, is there a way to find out which text view is being edited? Is there a way to access the text views from the main class?

推荐答案

在您的 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 = "..."
              }
      }
}

这样,您的视图控制器仍然不需要知道您的文本视图.

This way, your View Controller still does not need to know about your text views.

这篇关于如何从主类访问自定义集合视图单元格类中的文本视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆