Как организовать представления в tableViewController, используя ограничения, программно? - PullRequest
1 голос
/ 28 апреля 2019

Я пытаюсь реализовать UITableViewController.

Я написал код для пользовательского класса ячейки и UITableViewController, и у меня есть 3 вопроса для пользовательской ячейки:

1) Как я могу изменить свойства строки «title» и «description» в titleView и descriptionView, такие как размер, шрифт, цвет и т. Д.?

2) Как настроить изображение, чтобы оно оставалось слева, а название изображения - справа, когда они оба находятся над полем описания? Вот скриншот с текущим выводом

3) В моем titleView возникает проблема, когда я запускаю приложение, означающее, что любой пользователь может изменить заголовок, эта проблема не отображается в поле описания. Кто-нибудь может понять, почему? Я также добавлю скриншот ниже с этой проблемой: Каждый может изменить заголовок при использовании приложения

Вот код для UITableViewController:


struct CellData {
    var title: String?
    var description: String?
    var image: UIImage?
}

class TableViewController: UITableViewController {

    var data = [CellData]()

    override func viewDidLoad() {
        super.viewDidLoad()
        data = [CellData.init(title: "Dips", description: "Dips is one of the best exercises when it comes to building chest, triceps and even side delts. It's also good in the long run due to the fact that it implies your core a lot.", image: #imageLiteral(resourceName: "Dips"))]
        self.tableView.register(CustomCell.self, forCellReuseIdentifier: "custom")
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "custom") as! CustomCell
        cell.mainImage = data[indexPath.row].image
        cell.myDescription = data[indexPath.row].description
        cell.title = data[indexPath.row].title
        cell.layoutSubviews() // you don't have to scroll up to scale them properly
        return cell
    }

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

Вот код для пользовательской ячейки:

    class CustomCell: UITableViewCell {

    var title: String?
    var myDescription: String?
    var mainImage: UIImage?

    var titleView: UITextView = {
        var mainTitleView = UITextView()
        mainTitleView.translatesAutoresizingMaskIntoConstraints = false
        return mainTitleView
    }()

    var myDescriptionView: UITextView = {
        var textView = UITextView()
        textView.translatesAutoresizingMaskIntoConstraints = false // set this to false if you plan to add future constraints
        textView.isScrollEnabled = false
        return textView
    }()

    var mainImageView : UIImageView = {
        var imageView = UIImageView()
        imageView.translatesAutoresizingMaskIntoConstraints = false // same applies here
        imageView.contentMode = .scaleAspectFit
        return imageView
    }()


    // you just type init
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        self.addSubview(titleView)
        self.addSubview(myDescriptionView)
        self.addSubview(mainImageView)

        titleView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
        titleView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        titleView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
        titleView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true

        myDescriptionView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
        myDescriptionView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
        myDescriptionView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true

        mainImageView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
        mainImageView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
        mainImageView.bottomAnchor.constraint(equalTo: self.myDescriptionView.topAnchor).isActive = true
        mainImageView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        mainImageView.heightAnchor.constraint(equalToConstant: 120).isActive = true
    }



    // just type layout and Pick
    override func layoutSubviews() {
        super.layoutSubviews()

        if let title = title {
            titleView.text = title
        }
        if let description = myDescription {
            myDescriptionView.text = description
        }
        if let image = mainImage {
            mainImageView.image = image
        }
    }

        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder: ) has not been implemented")
        }
    }

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...