Контейнерное представление для экрана с несколькими табличными представлениями в iOS?
У меня есть пользовательский интерфейс, как показано на скриншоте. В настоящее время я сделал это с помощью таблиц. Экран представляет собой табличное представление со статической ячейкой прототипа в 4 строки. Один для заголовка, включая изображение профиля, следующий для биографии профиля, третий ряд для избранного, подписок, кнопки изображения события и последний ряд для контента, который является другим представлением таблицы.
Любимый раздел
Раздел подписки
Я использовал одно внутреннее табличное представление для содержимого со всеми элементами в избранном, подписках и событиях в одной ячейке. Одна загрузка, я скрываю другие элементы и показываю только один, в зависимости от значка нажмите.
Проблема заключается в несовместимости высоты ячейки в разделе избранного. Пробел присутствует в том случае, если на ярлыке более одной строки. В разделе подписок последний элемент касается панели вкладок.
Я отключил прокрутку для внешнего табличного представления, поэтому прокручивается только внутреннее табличное представление (раздел содержимого), что неприятно на небольших экранах.
class ProfileViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
profileTableView = ProfileSectionTableView() // inner table view
profileTableView.profileDelegate = self
profileSectionTableView.delegate = profileTableView
profileSectionTableView.dataSource = profileTableView
profileSectionTableView.rowHeight = UITableView.automaticDimension
profileSectionTableView.estimatedRowHeight = 44
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch (indexPath.row) {
case 0:
return 176
case 1:
return 72
case 2:
let height = self.view.frame.height - (176 + 72 + (self.tabBarController?.tabBar.frame.height)! + 8)
return height
default:
return UITableView.automaticDimension
}
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 44
}
}
Код табличного представления раздела контента:
class ProfileSectionTableView: UITableView, UITableViewDelegate, UITableViewDataSource, ProfileSectionViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let cell = updateTableCell(tableView, indexPath) as! ProfileCell
var height = UITableView.automaticDimension
if (ProfileData.profileViewType == .favourite) {
height = cell.favouritesTitleLabel.text!.height(withConstrainedWidth: cell.favouritesTitleLabel.frame.width - 64, font: UIFont(name: "Roboto", size: 17.0)!) + 28
} else if (ProfileData.profileViewType == .subscription) {
height = cell.subscriptionTitleLabel.text!.height(withConstrainedWidth: cell.subscriptionTitleLabel.frame.width - 64, font: UIFont(name: "Roboto", size: 17.0)!) + 16
}
return height
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
// ...
}
extension String {
func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil)
return ceil(boundingBox.height)
}
}
Как исправить разрыв между клетками? У меня есть линии ярлыка, установленные как 0
, Как расположить элементы интерфейса для таких экранов? Является ли вышеуказанный метод правильным? Или я должен использовать UIViewController с контейнером для разделов?
Связанный вопрос по этому вопросу Как изменить высоту ячейки внутренней таблицы представления ячейки в iOS?
1 ответ
В зависимости от вашей работы, я дружу только с таблицей на экране. Затем настройте tableView с помощью composionSection:[[String:Any]] data; любой элемент является данными раздела. Например: Избранное, Подписка... Для раздела: я установил keyId для раздела, раздела headSection, нижнего колонтитула и, конечно, раздела ячейки. Вы можете перейти к верхнему разделу для другого раздела.
Например:
// MARK: UITableViewDataSource
var composionSection = [[String: Any]]()
extension CountryDetailViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return composionSection.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let componentSection = self.composionSection[section] as? [String:Any]{
if let keyId = componentSection[kId] as? String, let object = componentSection[kObject] as? [String:Any] {
if keyId == kFavourites || keyId == kSubscription{
return object.count
}
}
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let componentSection = self.composionSection[indexPath.section] as? [String:Any]{
if let keyId = componentSection[kId] as? String, let object = componentSection[kObject] as? [String:Any] {
if keyId == kFavourites {
let cell = tableView.dequeueReusableCell(withIdentifier: identifierForViewCell, for: indexPath) as! ViewFavourites
return cell
}
else if keyId == kSubscription {
let cell = tableView.dequeueReusableCell(withIdentifier: identifierForViewCell, for: indexPath) as! ViewSubscription
return cell
}
}
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if let componentSection = self.composionSection[section] as? [String:Any]{
if let keyId = componentSection[kId] as? String, let object = componentSection[kObject] as? [String:Any] {
if keyId == kFavourites {
let sectionView = UIView()
return sectionView
}
else if keyId == kSubscription {
let sectionView = UIView()
return sectionView
}
}
}
return nil
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if let componentSection = self.composionSection[section] as? [String:Any] {
if let keyId = componentSection[kId] as? String {
if keyId == kFavourites {
return 80
}
else if keyId == kSubscription {
return 64 // or other
}
}
}
return 0
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}