UITableViewCell忽略自动布局

问题描述 投票:1回答:1

几天以来,我尝试了所有方法,甚至我尝试使用automaticDimension,并且估计RowHeight = 44,但都没有运气。我是UITableView的新手,并尝试进行练习。我到处都是stackoverflow等,没有运气。我不确定下面的代码在做什么错。

在视图控制器中:

reminder_tableview.frame = view.bounds
reminder_tableview.allowsSelection = false
reminder_tableview.estimatedRowHeight = 44
reminder_tableview.rowHeight = UITableView.automaticDimension
reminder_tableview.register(reminder_tableCell.self, forCellReuseIdentifier: "reminderList")
reminder_tableview.delegate = self
reminder_tableview.dataSource = self
tab2_body.addSubview(reminder_tableview)

并且在UITableViewDelegate的扩展名中,UITableViewDataSource:

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {return UITableView.automaticDimension}
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {return 50.0}
    func numberOfSections(in tableView: UITableView) -> Int {return reminder_category_user.count}
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if reminder_tableisready == true {
            let category_name = UILabel()
            category_name.frame = CGRect(x: 20, y: 0, width: view.frame.width - 80, height: 50)
            category_name.font = UIFont(name: "Arial", size: 30)
            category_name.text = reminder_category_user[section]
            category_name.textColor = UIColor.red

            let num_of_reminder = UILabel()
            num_of_reminder.frame = CGRect(x: view.frame.width - 75, y: 0, width: 70, height: 50)
            num_of_reminder.font = UIFont(name: "Arial", size: 30)
            num_of_reminder.text = String(reminder_final_table[section].count)
            num_of_reminder.textAlignment = .right
            num_of_reminder.textColor = UIColor.red

            let headerView = UIView()
            headerView.addSubview(category_name)
            headerView.addSubview(num_of_reminder)
            return headerView
        } else {
            return UIView()
        }
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if reminder_tableisready == true {
            return reminder_final_table[section].count
        } else {
            return 0
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "reminderList") as! reminder_tableCell
        cell.backgroundColor = UIColor(red: 15/255, green: 15/255, blue: 15/255, alpha: 1)
        cell.frame.size.height = 100
        cell.textLabel?.text = reminder_final_table[indexPath.section][indexPath.row].pre_title
        cell.textLabel?.font = UIFont(name: "Arial", size: 18)
        cell.textLabel?.numberOfLines = 0
        cell.textLabel?.lineBreakMode = .byWordWrapping
        cell.textLabel?.sizeToFit()

        let getdatefromdatedue = Date(timeIntervalSince1970: TimeInterval(reminder_final_table[indexPath.section][indexPath.row].pre_datedue))
        let duedateformat = DateFormatter()
        duedateformat.dateFormat = "MMMM d, yyyy\nh:mm a"

        if reminder_final_table[indexPath.section][indexPath.row].pre_datedue != 0 {
            cell.layoutMargins.right = 160
            cell.reminder_date_due.text = "Date Due\n\(duedateformat.string(from: getdatefromdatedue))"
        } else {
            cell.reminder_date_due.text = ""
        }
        cell.reminder_date_due.textColor = UIColor.red
        cell.reminder_date_due.textAlignment = .right
        cell.reminder_date_due.numberOfLines = 4
        cell.reminder_date_due.font = UIFont(name: "Arial", size: 15)

        return cell
    }
}

class reminder_tableCell: UITableViewCell {
    var reminder_date_due = UILabel()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
        reminder_date_due.frame = CGRect(x: reminder_tableview.frame.width - 155, y: 0, width: 150, height: 66)
        addSubview(reminder_date_due)
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
ios swift uitableview autolayout
1个回答
0
投票

首先,我强烈建议您[[通常不要使用魔术值],因为如果要支持所有屏幕尺寸,它将很快失去控制。

此外,由于您正在预先计算所有帧,因此实际上您并未使用自动版式。

Apple引入了Auto Layout,它具有基于约束的行为,因此您不必为每种屏幕尺寸手动完成所有帧计算工作。

[Auto Layout将根据您设置的约束/锚点,无论是通过使用故事板还是以编程方式,来动态计算所有视图的大小和位置。

[我还在您的代码中看到您使用的是一个提醒代码表视图变量,它引用了您的UITableView,并让我认为您正在将表视图用作全局属性:您应该不惜一切代价避免这样做。] >

对于命名属性或方法,最佳实践是使用

Camel Case,因为这将使您的代码更易于阅读和理解

。驼峰式大小写是指您使用小写字母开头的名称,然后将第二个字母的第一个字母和所有后续单词的首字母大写,例如:
let reminderTableIsReady = false var reminderDueDateLabel: UILabel? func scheduleNewReminder() {} // ...
并且通常使用的命名类,枚举或结构的方式是

上驼峰式案例

class ReminderTableViewCell: UITableViewCell {}
现在返回您的代码,我对其进行了重构,并制作了一个最小版本,以供您查看如何在UITableViewUITableViewCell下使用自动版式和约束。 

我没有从代码中添加所有内容,但我认为您可以轻松地自己完成其余的工作:

ReminderViewController:

import UIKit // You don't have to use this Date extension below, but this will improve the performances by keeping only one formatter instance, since you will be reusing it in all your UITableViewCell: extension Date { static let formatter = DateFormatter() func formatted() -> String { Date.formatter.dateFormat = "MMMM d, yyyy, hh:mm a" return Date.formatter.string(from: self) } } struct Reminder { let dueDate: TimeInterval } class ReminderViewController: UIViewController { private let reuseIdentifier = "reuseIdentifier" private var reminders = [[Reminder]]() private let tableView = UITableView(frame: .zero, style: .grouped) override func viewDidLoad() { super.viewDidLoad() setupViews() setupConstraints() } func setupViews() { tableView.delegate = self tableView.dataSource = self tableView.register(ReminderTableViewCell.self, forCellReuseIdentifier: reuseIdentifier) view.addSubview(tableView) reminders = // ... Set your data here } func setupConstraints() { tableView.translatesAutoresizingMaskIntoConstraints = false tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true } } extension ReminderViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return nil } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return CGFloat.leastNonzeroMagnitude } } extension ReminderViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return reminders.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section > reminders.count { return 0 } return reminders[section].count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! ReminderTableViewCell let reminder = reminders[indexPath.section][indexPath.row] let date = Date(timeIntervalSince1970: reminder.dueDate) if reminder.dueDate > 0 { cell.dueDateLabel.text = "Due Date: \(date.formatted())" } return cell } }

ReminderTableViewCell:

class ReminderTableViewCell: UITableViewCell { let dueDateLabel = UILabel() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupViews() setupConstraints() } func setupViews() { dueDateLabel.textColor = .red dueDateLabel.textAlignment = .right dueDateLabel.numberOfLines = 4 dueDateLabel.font = UIFont(name: "Arial", size: 15) contentView.addSubview(dueDateLabel) } func setupConstraints() { dueDateLabel.translatesAutoresizingMaskIntoConstraints = false dueDateLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 20).isActive = true dueDateLabel.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 20).isActive = true dueDateLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -20).isActive = true dueDateLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -20).isActive = true } required init?(coder: NSCoder) { fatalError() } }
© www.soinside.com 2019 - 2024. All rights reserved.