如何将UITableView子类化以在其他viewControllers中使用

时间:2017-09-29 00:01:49

标签: ios swift xcode

我正在为tableview创建一个子类,我希望在我的所有应用程序中使用它。我的问题是当我设置fields变量时,tableview仍为空。我假设fields变量在新的ViewController中设置时没有设置。感谢您的帮助。

MySubClass

import UIKit
import LGButton

class RquestTableViewController: UITableViewController {
    var fields:[UIView]

    override func viewDidLoad() {
        super.viewDidLoad()
        viewSetup()
    }

    func viewSetup(){
        tableView.register(CustomFormCell.self, forCellReuseIdentifier: labelReuseCellIdentifier)
        self.tableView.tableFooterView = UIView.init(frame: CGRect.zero)

    }
}
//MARK: Delegate
extension RquestTableViewController {
    override func numberOfSections(in tableView: UITableView) -> Int {
        return fields.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: self.labelReuseCellIdentifier, for: indexPath) as! CustomFormCell
        let itemView = fields[indexPath.row]
        cell.viewPassed = itemView
        cell.backgroundColor = .clear
        if let _ = itemView as? UILabel {
            cell.separatorInset = UIEdgeInsetsMake(0, cell.bounds.size.width, 0, 0)
            return cell
        }
        if let _ = itemView as? UIButton {
            cell.separatorInset = UIEdgeInsetsMake(0, cell.bounds.size.width, 0, 0)
            return cell
        }
        if let _ = itemView as? LGButton {
            cell.separatorInset = UIEdgeInsetsMake(0, cell.bounds.size.width, 0, 0)
            return cell
        }
        return  cell
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 40.0
    }
}

MyNewViewController

class NewRquestViewController: RquestTableViewController {

    lazy var password:JVFloatLabeledTextField = {
        let v = JVFloatLabeledTextField()
        v.placeholder = "Password"
        return v
    }()
    override func viewDidLoad() {
       super.viewDidLoad()
        fields = [password]
    }
}

1 个答案:

答案 0 :(得分:0)

您是否确认fields确实没有正确设置?我认为没有理由不这样做。但我确实看到了另一个问题:除了覆盖numberOfSections(in:)tableView(_,cellForRowAt:)之外,您还必须覆盖tableView(_,numberOfRowsInSection:)。您现在拥有的是numberOfSections(in:)返回字段数,但tableView(_,cellForRowAt:)期望使用字段填充。这意味着当tableView(_,cellForRowAt:)section时,0将仅被称为 ,因此最多只会看到一个字段。相反,请更改numberOfSections(in:)以返回1,并实施tableView(_,numberOfRowsInSection:)以返回fields.count