Загрузка содержимого tablecell из пользовательского представления - PullRequest
0 голосов
/ 07 января 2020

Я новичок в swift и ниже проблема, с которой я сталкиваюсь, у меня есть табличное представление, и одна из ячеек - customCell, которая загружает настраиваемое представление. Нет сбоев, но ограничения и цвет фона для ячейки таблицы не отображаются. Пожалуйста, обратитесь к приведенному ниже коду

class ViewController: UIViewController, UITableViewDataSource {


    let data = ["Apple", "Banana", "Orange", "Grape", "Banana", "Orange", "Grape", "Banana", "Orange", "Grape", "Banana", "Orange", "Grape", "Banana", "Orange", "Grape", "Banana", "Orange", "Grape", "Banana", "Orange", "Grape", "Banana", "Orange", "Grape", "Banana", "Orange", "Grape", "Banana", "Orange", "Grape"]
    @IBOutlet weak var tableView: UITableView!

    @IBOutlet weak var customView: CustomView!
    override func viewDidLoad() {
        super.viewDidLoad()
        customView.myLabel.text = "Hey hey"
        customView.backgroundColor = UIColor.green
        tableView.dataSource = self
        tableView.register(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "customCell")
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        tableView.tableFooterView = UIView()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        data.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 3 {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as? CustomTableViewCell else { return UITableViewCell()}

//            cell.layoutSubviews()
//            cell.layoutIfNeeded()
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
            cell.textLabel?.text = data[indexPath.row]
            return cell
        }


    }
}


Custom View:
class CustomView: UIView {

    @IBOutlet var contentView: UIView!
    @IBOutlet weak var myLabel: UILabel!

    let kCONTENT_XIB_NAME = "CustomView"
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }

    private func commonInit() {
        Bundle.main.loadNibNamed(kCONTENT_XIB_NAME, owner: self, options: nil)
        contentView.fixInView(self)
    }

}

extension UIView
{
    func fixInView(_ container: UIView!) -> Void{
        self.translatesAutoresizingMaskIntoConstraints = false;
        self.frame = container.frame;
        container.addSubview(self);
        NSLayoutConstraint(item: self, attribute: .leading, relatedBy: .equal, toItem: container, attribute: .leading, multiplier: 1.0, constant: 0).isActive = true
        NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: container, attribute: .trailing, multiplier: 1.0, constant: 0).isActive = true
        NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: container, attribute: .top, multiplier: 1.0, constant: 0).isActive = true
        NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: container, attribute: .bottom, multiplier: 1.0, constant: 0).isActive = true
    }
}

Custom Tablecell:
class CustomTableViewCell: UITableViewCell {

    @IBOutlet weak var cellContentView: CustomView!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        cellContentView.backgroundColor = UIColor.blue
    }

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

        // Configure the view for the selected state
    }

}

Ниже приведена структура раскадровки enter image description here

При запуске приложения ниже приведен скриншот он отображает enter image description here

Проблема 1 : строка 3 - это пользовательский вид, фон которого должен быть синим, как установлено в пользовательском классе ячеек

Проблема 2 : В моем viewcontroller, даже после установки зеленого цвета фона, почему он не отображает этот цвет. «Оранжевый» используется в раскадровке при создании представления

Проблема 3 : Если у меня есть несколько динамических c элементов управления, как будет установлена ​​высота ячейки.

Пожалуйста, совет. Я поражен здесь

1 Ответ

0 голосов
/ 08 января 2020

Для Выпуск 1 , Вы должны добавить пользовательское представление в качестве представления содержимого ячейки. Просто добавьте следующую строку:

contentView.addSubview(cellContentView)
cellContentView.backgroundColor = UIColor.blue
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...