【问题标题】:Segue to new view when UITextField within Custom TableView Cell tapped当点击自定义 TableView 单元格中的 UITextField 时转到新视图
【发布时间】:2017-01-07 16:11:31
【问题描述】:

我在自定义 UITableViewCell 中有一个 UITextField。

当点击自定义单元格中的 UITextField 时,我需要切换到新的视图控制器。

尝试的解决方案

我尝试在 CustomTableViewCell 类中使用

public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    print("Text Field Tapped")
    return false 
}

但是这不起作用,因为 performSegue 是一个 ViewController 函数。然后我尝试了

func someAction() {
    performSegue(withIdentifier: "identifier", sender: self) 
}

在 MyViewController 类中,但这也不起作用(不知道为什么)。这是我的两个类的样子:

MyViewController(持有 UITableView)

import UIKit

class MyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var tableView: UITableView!

    override func viewDidLoad() {

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:SearchTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cell") as! SearchTableViewCell

        return cell
    }
}

CustomTableViewCell

import UIKit

class CustomTableViewCell: UITableViewCell, UITextFieldDelegate {
    @IBOutlet weak var someTextField: UITextField!

    override func awakeFromNib() {
        super.awakeFromNib()

        self.someTextField.delegate = self
    }
}

非常感谢您的聪明人可以提供的任何帮助:)

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    这样的事情应该可以工作:

    class TableViewController: UITableViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
    
            tableView.estimatedRowHeight = 44
            tableView.rowHeight = UITableViewAutomaticDimension
        }
        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 1
        }
    
        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "TFCell", for: indexPath) as! TFCell
            cell.textField.delegate = self
            return cell
        }
    }
    
    extension TableViewController: UITextFieldDelegate {
        func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
            performSegue(withIdentifier: "TFSegue", sender: textField)
            return false
        }
    }
    
    class TFCell: UITableViewCell {
        @IBOutlet weak var textField: UITextField!
    }
    

    “TFSegue”是从“TableViewController”到在storyboard中创建的targetviewcontroller的segue。有什么不清楚的地方欢迎追问!

    【讨论】:

    • 非常感谢您的帮助!谢谢。不确定您是否对 Swift 中的自定义 SearchBars 有任何经验,但如果有,您可以看看这篇文章:stackoverflow.com/questions/41641521/… 吗?再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多