OStack程序员社区-中国程序员成长平台

标题: ios - 从 UITextView Swift 2 获取文本 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 13:33
标题: ios - 从 UITextView Swift 2 获取文本

我正在使用 swift 2 做一个 iOS 项目,我有一个带有自定义单元格的 UITableView。我有一个带有 UITextView 和简单标签的单元格,当它被修改时我不想得到这个 UITextView 的值,但它不像 UITextFields,我不能在编辑开始方法上使用。我该怎么做?

这是我定义自定义单元格的代码:

let cell = tableView.dequeueReusableCellWithIdentifier(CurrentFormTableView.CellIdentifiers.ParagraphCell, forIndexPath: indexPath) as! ParagraphCell
                cell.display(block)
                cell.selectionStyle = UITableViewCellSelectionStyle.None
                tableView.rowHeight = UITableViewAutomaticDimension
                tableView.estimatedRowHeight = 160.0
                return cell

这是我的 ParagraphCell.swift

import UIKit

protocol ParagraphCell {
    func update ParagraphCell(cell: ParagraphCell, rep: String)
}

class ParagraphCell: UITableViewCell {

    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var answerField: UITextView!


    var delegate: ParagraphCell Delegate?

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        let borderColor : UIColor = UIColor(red: 0.85, green: 0.85, blue: 0.85, alpha: 1.0)
        answerField.layer.borderWidth = 0.5
        answerField.layer.borderColor = borderColor.CGColor
        answerField.layer.cornerRadius = 5.0

    }

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

        // Configure the view for the selected state
    }

    func display(block: Block){
        titleLabel.text = block.title
        answerField.text = ""
    }

//THIS METHOD IS NEVER CALLED... 
    func textViewDidChange(textView: UITextView) { //Handle the text changes here
        print(textView.text); //the textView parameter is the textView where text was changed
        delegate?.update ParagraphCell(self, rep: textView.text)
    }


}



Best Answer-推荐答案


您需要在 awakeFromNib 中添加 answerField.delegate = self 以接收委托(delegate)回调。

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
    let borderColor : UIColor = UIColor(red: 0.85, green: 0.85, blue: 0.85, alpha: 1.0)
    answerField.layer.borderWidth = 0.5
    answerField.layer.borderColor = borderColor.CGColor
    answerField.layer.cornerRadius = 5.0
    answerField.delegate = self // create delegate reference
}

您还需要将 UITextViewDelegate 添加到您的类协议(protocol)声明中:

class ParagraphCell: UITableViewCell, UITextViewDelegate { }

关于ios - 从 UITextView Swift 2 获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37131507/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4