SnapKit - UITableView height is not change with dynamical content of cell - ios

I'm a beginner in SnapKit, I want to implement a UITableViewController with SnapKit, each row have two UILabel, one of them is Title and another one is Value.
My issue is the height of the row in UITableView not changed according to the content of each row.
here is my code:
class ViewController:
import UIKit
import SnapKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// MARK: Property List
var list: NSMutableArray?
let myTableView: UITableView = {
let table = UITableView()
return table
}()
//MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
self.myTableView.rowHeight = UITableView.automaticDimension
self.myTableView.estimatedRowHeight = 100
title = "TableView Page"
setup()
setupViews()
}
// MAKR: Setup View
func setup() {
self.view.backgroundColor = .white
navigationController?.navigationBar.prefersLargeTitles = true
}
func setupViews () {
self.view.addSubview(myTableView)
myTableView.snp.makeConstraints { make in
make.top.left.bottom.right.equalTo(10)
}
myTableView.register(CustomCell.self, forCellReuseIdentifier: CustomCell.customCell)
myTableView.delegate = self
myTableView.dataSource = self
}
// MARK: TableView DataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: CustomCell.customCell, for: indexPath) as! CustomCell
cell.title.text = "title is lognest??"
cell.value.text = (indexPath.row % 2 == 0) ?
"longest value longest value longest value longest value longest value longest value longest value for text"
: "short value"
cell.title.snp.makeConstraints { (make) in
make.top.equalTo(cell.value.snp.top)
make.left.equalTo(20)
make.trailing.equalTo(cell.value.snp.leading)
}
cell.value.snp.makeConstraints { (make) in
make.right.equalTo(-20)
make.top.equalTo(cell.title.snp.top)
make.bottom.equalTo(-10)
}
NSLog("value height is: \(cell.value.frame.height)")
NSLog("cell height is: \(cell.frame.height)")
return cell;
}
}
class CustomCell:
// MARK: custom cell
class CustomCell: UITableViewCell {
// MARK: Property
static var customCell = "cell"
public var title:UILabel = {
let tit = UILabel()
tit.setContentHuggingPriority(.defaultLow, for: .horizontal)
tit.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
tit.textColor = .black
tit.alpha = 0.6
return tit
}()
public var value:UILabel = {
let val = UILabel()
val.textColor = .black
val.setContentHuggingPriority(.defaultHigh, for: .horizontal)
val.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
val.lineBreakMode = NSLineBreakMode.byWordWrapping
val.numberOfLines = 0
val.alpha = 0.75
return val
}()
// MARK: initializer
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.addSubview(title)
self.addSubview(value)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init?(coder aDecoder: NSCoder)")
}
}
And this is console logs:
snapkitTest[26345:1387159] cell height is: 44.0
snapkitTest[26345:1387159] value height is: 0.0

1- You have to add the label to
self.contentView.addSubview(title)
2- You need to set bottom constraint to contentView
title.snp.makeConstraints { (make) -> Void in
make.trailing.equalTo(value.snp.leading)
make.top.equalTo(self.contentView.snp.top).inset(10)
make.left.equalTo(20)
}
value.snp.makeConstraints { (make) -> Void in
make.right.equalTo(-40)
make.top.equalTo(self.contentView.snp.top).inset(10)
make.bottom.equalTo(-10)
}
Also transfer this constraints to init of cell custom class , as not to re-add constraints every scroll of tableView

Related

UITableView CustomCell Reuse (ImageView in CustomCell)

I'm pretty new to iOS dev and I have an issue with UITableViewCell.
I guess it is related to dequeuing reusable cell.
I added an UIImageView to my custom table view cell and also added a tap gesture to make like/unlike function (image changes from an empty heart(unlike) to a filled heart(like) as tapped and reverse). The problem is when I scroll down, some of the cells are automatically tapped. I found out why this is happening, but still don't know how to fix it appropriately.
Below are my codes,
ViewController
import UIKit
struct CellData {
var title: String
var done: Bool
}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var models = [CellData]()
private let tableView: UITableView = {
let table = UITableView()
table.register(TableViewCell.self, forCellReuseIdentifier: TableViewCell.identifier)
return table
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
tableView.frame = view.bounds
tableView.delegate = self
tableView.dataSource = self
configure()
}
private func configure() {
self.models = Array(0...50).compactMap({
CellData(title: "\($0)", done: false)
})
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return models.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let model = models[indexPath.row]
guard let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as? TableViewCell else {
return UITableViewCell()
}
cell.textLabel?.text = model.title
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
tableView.reloadData()
}
}
TableViewCell
import UIKit
class TableViewCell: UITableViewCell {
let mainVC = ViewController()
static let identifier = "TableViewCell"
let likeImage: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(systemName: "heart")
imageView.tintColor = .darkGray
imageView.isUserInteractionEnabled = true
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(likeImage)
layout()
//Tap Gesture Recognizer 실행하기
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapImageView(_:)))
likeImage.addGestureRecognizer(tapGestureRecognizer)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
}
override func prepareForReuse() {
super.prepareForReuse()
}
private func layout() {
likeImage.widthAnchor.constraint(equalToConstant: 30).isActive = true
likeImage.heightAnchor.constraint(equalToConstant: 30).isActive = true
likeImage.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
likeImage.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -20).isActive = true
}
#objc func didTapImageView(_ sender: UITapGestureRecognizer) {
if likeImage.image == UIImage(systemName: "heart.fill"){
likeImage.image = UIImage(systemName: "heart")
likeImage.tintColor = .darkGray
} else {
likeImage.image = UIImage(systemName: "heart.fill")
likeImage.tintColor = .systemRed
}
}
}
This gif shows how it works now.
enter image description here
I've tried to use "done" property in CellData structure to capture the status of the uiimageview but failed (didn't know how to use that in the correct way).
I would be so happy if anyone can help this!
You've already figured out that the problem is cell reuse.
When you dequeue a cell to be shown, you are already setting the cell label's text based on your data:
cell.textLabel?.text = model.title
you also need to tell the cell whether to show the empty or filled heart image.
And, when the user taps that image, your cell needs to tell the controller to update the .done property of your data model.
That can be done with either a protocol/delegate pattern or, more commonly (particularly with Swift), using a closure.
Here's a quick modification of the code you posted... the comments should give you a good idea of what's going on:
struct CellData {
var title: String
var done: Bool
}
class ShinViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var models = [CellData]()
private let tableView: UITableView = {
let table = UITableView()
table.register(ShinTableViewCell.self, forCellReuseIdentifier: ShinTableViewCell.identifier)
return table
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
tableView.frame = view.bounds
tableView.delegate = self
tableView.dataSource = self
configure()
}
private func configure() {
self.models = Array(0...50).compactMap({
CellData(title: "\($0)", done: false)
})
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return models.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: ShinTableViewCell.identifier, for: indexPath) as! ShinTableViewCell
let model = models[indexPath.row]
cell.myLabel.text = model.title
// set the "heart" to true/false
cell.isLiked = model.done
// closure
cell.callback = { [weak self] theCell, isLiked in
guard let self = self,
let pth = self.tableView.indexPath(for: theCell)
else { return }
// update our data
self.models[pth.row].done = isLiked
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
class ShinTableViewCell: UITableViewCell {
// we'll use this closure to communicate with the controller
var callback: ((UITableViewCell, Bool) -> ())?
static let identifier = "TableViewCell"
let likeImageView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(systemName: "heart")
imageView.tintColor = .darkGray
imageView.isUserInteractionEnabled = true
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
let myLabel: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
// we'll load the heart images once in init
// instead of loading them every time they change
var likeIMG: UIImage!
var unlikeIMG: UIImage!
var isLiked: Bool = false {
didSet {
// update the image in the image view
likeImageView.image = isLiked ? likeIMG : unlikeIMG
// update the tint
likeImageView.tintColor = isLiked ? .systemRed : .darkGray
}
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
// make sure we load the heart images
guard let img1 = UIImage(systemName: "heart"),
let img2 = UIImage(systemName: "heart.fill")
else {
fatalError("Could not load the heart images!!!")
}
unlikeIMG = img1
likeIMG = img2
// add label and image view
contentView.addSubview(myLabel)
contentView.addSubview(likeImageView)
layout()
//Tap Gesture Recognizer 실행하기
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapImageView(_:)))
likeImageView.addGestureRecognizer(tapGestureRecognizer)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
}
override func prepareForReuse() {
super.prepareForReuse()
}
private func layout() {
// let's use the "built-in" margins guide
let g = contentView.layoutMarginsGuide
// image view bottom constraint
let bottomConstraint = likeImageView.bottomAnchor.constraint(equalTo: g.bottomAnchor)
// this will avoid auto-layout complaints
bottomConstraint.priority = .required - 1
NSLayoutConstraint.activate([
// constrain label leading
myLabel.leadingAnchor.constraint(equalTo: g.leadingAnchor),
// center the label vertically
myLabel.centerYAnchor.constraint(equalTo: g.centerYAnchor),
// constrain image view trailing
likeImageView.trailingAnchor.constraint(equalTo: g.trailingAnchor),
// constrain image view to 30 x 30
likeImageView.widthAnchor.constraint(equalToConstant: 30),
likeImageView.heightAnchor.constraint(equalTo: likeImageView.widthAnchor),
// constrain image view top
likeImageView.topAnchor.constraint(equalTo: g.topAnchor),
// activate image view bottom constraint
bottomConstraint,
])
}
#objc func didTapImageView(_ sender: UITapGestureRecognizer) {
// toggle isLiked (true/false)
isLiked.toggle()
// inform the controller, so it can update the data
callback?(self, isLiked)
}
}

Why doesn't my table view cell class instance run its initializer in my Swift code?

I have a custom subclass of UITableViewCell shown below
class GroupSelectionTableViewCell: UITableViewCell {
// MARK: - Properties
var groupSelectionLabel: UILabel = {
let label = UILabel()
label.textColor = .white
label.backgroundColor = .clear
label.font = UIFont.systemFont(ofSize: 18)
return label
}()
var groupSelectionImageView: UIImageView = {
let iv = UIImageView()
iv.backgroundColor = .clear
iv.setHeight(height: 25)
iv.setWidth(width: 25)
iv.contentMode = .scaleAspectFill
return iv
}()
// MARK: - LifeCycle
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
configureUI()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Helper Functions
private func configureUI() {
self.addSubview(groupSelectionLabel)
groupSelectionLabel.centerY(inView: self)
groupSelectionLabel.anchor(left: self.leftAnchor, paddingLeft: 12)
self.addSubview(groupSelectionImageView)
groupSelectionImageView.centerY(inView: self)
groupSelectionImageView.anchor(right: self.rightAnchor, paddingRight: 12)
self.backgroundColor = .black
self.selectionStyle = .none
}
}
and a custom subclass of UITableView shown below...
class GroupSelectionView: UITableView {
// MARK: - Properties
private let cellID = "GroupSelectionTableViewCell"
override init(frame: CGRect, style: UITableView.Style) {
super.init(frame: frame, style: style)
backgroundColor = .red
setHeight(height: 450)
setWidth(width: 300)
register(GroupSelectionTableViewCell.self, forCellReuseIdentifier: cellID)
rowHeight = 60
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension GroupSelectionView: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
return
}
}
extension GroupSelectionView: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
6
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! GroupSelectionTableViewCell
cell.groupSelectionLabel.text = "None"
cell.groupSelectionImageView.image = UIImage(named: "Tick")
return cell
}
}
But when I add my table view instance to a UIView() as a subview the table view cell class isn't running its initializer. Am I using the register method correctly? I have tried instantiating the table view subclass and putting a print statement in the initializer of the table view cell subclass but it doesn't get printed. Am I forgetting to set some property on the table view subclass? Do I need to use the Nib version of register instead? Any help would be greatly appreciated.
Forgot to set the dataSource and the delegate!

Swift UITableView separator hidden until scroll

I have implemented a custom table view cell which appears but without the separator until you scroll. In the viewDidAppear I have set the separator style, the label border is not overlapping the cell edges. Help
Before Scrolling
After Scrolling
Larger Sim Window
On device testing
The pattern is MVVM with a custom cell.
Model
import Foundation
struct OAuthList {
let providers: [String]
init() {
self.providers = OAuthProviders.providers
}
}
View Model
import Foundation
struct OAuthListViewModel {
var providerList: [String]
init(providers: [String]) {
self.providerList = providers
}
}
LoginViewController
import UIKit
class LoginViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet var tableView: UITableView!
var providerButtons = OAuthListViewModel(providers: OAuthProviders.providers)
override func viewDidLoad() {
super.viewDidLoad()
let attributes = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 17)]
self.navigationController?.navigationBar.titleTextAttributes = attributes
self.navigationController?.navigationBar.isTranslucent = false
self.navigationController?.navigationBar.barTintColor = #colorLiteral(red: 1, green: 0.738589704, blue: 0.9438112974, alpha: 1)
self.navigationItem.title = "LOGIN / SIGNUP"
self.navigationItem.leftBarButtonItem?.tintColor = .white
self.navigationItem.leftBarButtonItem?.isEnabled = false
self.tableView.separatorColor = .white
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.register(CustomCell.self, forCellReuseIdentifier: TextCellIdentifier.textCellIdentifier)
self.tableView.layoutMargins = UIEdgeInsets.zero
self.tableView.separatorInset = UIEdgeInsets.zero
self.tableView.tableFooterView = UIView()
}
}
extension LoginViewController {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return providerButtons.providerList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: TextCellIdentifier.textCellIdentifier, for: indexPath) as! CustomCell
let row = indexPath.row
cell.backgroundColor = #colorLiteral(red: 1, green: 0.738589704, blue: 0.9438112974, alpha: 1)
cell.buttonLabel.text = providerButtons.providerList[row]
cell.layoutMargins = UIEdgeInsets.zero
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(providerButtons.providerList[indexPath.row])
}
}
Custom Cell
class CustomCell: UITableViewCell {
var labelText: String?
var buttonLabel: UILabel = {
var label = UILabel()
return label
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: TextCellIdentifier.textCellIdentifier)
self.addSubview(buttonLabel)
buttonLabel.translatesAutoresizingMaskIntoConstraints = false
buttonLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
buttonLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
buttonLabel.textColor = UIColor.white
}
override func layoutSubviews() {
if let labelText = labelText {
buttonLabel.text = labelText
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
You can hide the separator and simply add UIView to act as a separator inside your custom cells
Enlarge your simulator window or try it on an actual device not sim.
When the sim window is small enough it can have a hard time displaying separators in a tableview since the separators are normally only 0.5pt in height.
A good indicator that the issue I mentioned above is occurring is when you scroll the tableview on the simulator and random separators start to appear while some are hidden. Which is what appears to be happening in your second screenshot.

How to update height Constraints by SnapKit and update cell height?

I have a TableViewCell and two button to switch different constrain.
I want to update it's height constrain and cell height.
like following pic1
when I click buttonB, the view will change like pic2
Then I click buttonA, the view will back to pic1
I try to modify constrains, but I fail to update height.
Have any idea or answer to me?
Thanks
pic1
pic2
Here is code:
class CellContainView: UIView {
let buttonA: UIButton = { () -> UIButton in
let ui = UIButton()
ui.titleLabel?.numberOfLines = 0
ui.setTitle("Click\nA", for: .normal)
ui.backgroundColor = UIColor.blue
return ui
}()
let buttonB: UIButton = { () -> UIButton in
let ui = UIButton()
ui.titleLabel?.numberOfLines = 0
ui.setTitle("Click\nB", for: .normal)
ui.backgroundColor = UIColor.gray
return ui
}()
let buttonC: UIButton = { () -> UIButton in
let ui = UIButton()
ui.titleLabel?.numberOfLines = 0
ui.setTitle("Click\nC", for: .normal)
ui.backgroundColor = UIColor.brown
return ui
}()
let labelA: UILabel = { () -> UILabel in
let ui = UILabel()
ui.text = "Test"
return ui
}()
let viewA: UIView = { () -> UIView in
let ui = UIView()
ui.backgroundColor = UIColor.red
return ui
}()
override init(frame: CGRect) {
super.init(frame: frame)
addUI()
addConstrain()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addUI() {
self.addSubview(buttonA)
self.addSubview(buttonB)
self.addSubview(buttonC)
self.addSubview(labelA)
self.addSubview(viewA)
}
func addConstrain() {
buttonA.snp.makeConstraints { (make) in
make.left.top.equalToSuperview()
make.height.equalTo(60)
}
buttonB.snp.makeConstraints { (make) in
make.left.equalTo(buttonA.snp.right)
make.top.right.equalToSuperview()
make.width.equalTo(buttonA.snp.width)
make.height.equalTo(buttonA.snp.height)
}
buttonC.snp.makeConstraints { (make) in
make.left.equalTo(15)
make.right.equalTo(-15)
make.bottom.equalTo(-15)
make.height.equalTo(50)
}
labelA.snp.makeConstraints { (make) in
make.left.equalTo(15)
make.top.equalTo(buttonA.snp.bottom).offset(15)
make.width.equalTo(195)
make.height.equalTo(50)
}
viewA.snp.makeConstraints { (make) in
make.left.equalTo(labelA.snp.right)
make.top.equalTo(buttonA.snp.bottom).offset(15)
make.right.equalTo(-15)
make.height.equalTo(50)
make.bottom.equalTo(buttonC.snp.top).offset(-10)
}
}
func updateConstrain(sender: UIButton) {
switch sender {
case buttonA:
viewA.snp.updateConstraints { (make) in
make.height.equalTo(50)
}
case buttonB:
viewA.snp.updateConstraints { (make) in
make.height.equalTo(150)
}
default:
break
}
}
}
class TestTableViewCell: UITableViewCell {
let cellContainView: CellContainView = { () -> CellContainView in
let ui = CellContainView()
ui.backgroundColor = UIColor.orange
return ui
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.addSubview(cellContainView)
cellContainView.snp.makeConstraints { (make) in
make.left.top.equalTo(15)
make.bottom.right.equalTo(-15)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let tableView: UITableView = { () -> UITableView in
let ui = UITableView()
return ui
}()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44
tableView.register(TestTableViewCell.self, forCellReuseIdentifier: "TestTableViewCell")
tableView.tableFooterView = UIView()
self.view.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.top.left.right.bottom.equalToSuperview()
}
}
#objc func buttonAClicked(sender: UIButton) {
let index = IndexPath(row: 0, section: 0)
let cell = tableView.cellForRow(at: index) as! TestTableViewCell
cell.cellContainView.updateConstrain(sender: sender)
tableview.reloadData()
}
#objc func buttonBClicked(sender: UIButton) {
let index = IndexPath(row: 0, section: 0)
let cell = tableView.cellForRow(at: index) as! TestTableViewCell
cell.cellContainView.updateConstrain(sender: sender)
tableview.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TestTableViewCell", for: indexPath) as! TestTableViewCell
cell.cellContainView.buttonA.addTarget(self, action: #selector(buttonAClicked), for: .touchUpInside)
cell.cellContainView.buttonB.addTarget(self, action: #selector(buttonBClicked), for: .touchUpInside)
return cell
}
}
Update constrain problem when I click butttonB (Add update viewA heightConstrain & tableview.reloadData()):
TestCellUpdateHeight[29975:5195310] [LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"<SnapKit.LayoutConstraint:0x6040000a4320#CellContainView.swift#75 UIButton:0x7fa1d0d0d680.height == 60.0>",
"<SnapKit.LayoutConstraint:0x6040000a49e0#CellContainView.swift#89 UIButton:0x7fa1d0d10610.height == 50.0>",
"<SnapKit.LayoutConstraint:0x6040000a51c0#CellContainView.swift#104 UIView:0x7fa1d0d11130.height == 150.0>",
"<SnapKit.LayoutConstraint:0x6040000a4800#CellContainView.swift#80 UIButton:0x7fa1d0d0f7b0.top == TestCellUpdateHeight.CellContainView:0x7fa1d0d0d470.top>",
"<SnapKit.LayoutConstraint:0x6040000a4a40#CellContainView.swift#82 UIButton:0x7fa1d0d0f7b0.height == UIButton:0x7fa1d0d0d680.height>",
"<SnapKit.LayoutConstraint:0x6040000a4ec0#CellContainView.swift#88 UIButton:0x7fa1d0d10610.bottom == TestCellUpdateHeight.CellContainView:0x7fa1d0d0d470.bottom - 15.0>",
"<SnapKit.LayoutConstraint:0x6040000a5100#CellContainView.swift#102 UIView:0x7fa1d0d11130.top == UIButton:0x7fa1d0d0f7b0.bottom + 15.0>",
"<SnapKit.LayoutConstraint:0x6040000a5220#CellContainView.swift#105 UIView:0x7fa1d0d11130.bottom == UIButton:0x7fa1d0d10610.top - 10.0>",
"<SnapKit.LayoutConstraint:0x6040000a52e0#TestTableViewCell.swift#26 TestCellUpdateHeight.CellContainView:0x7fa1d0d0d470.top == TestCellUpdateHeight.TestTableViewCell:0x7fa1d208a000.top + 15.0>",
"<SnapKit.LayoutConstraint:0x6040000a53a0#TestTableViewCell.swift#27 TestCellUpdateHeight.CellContainView:0x7fa1d0d0d470.bottom == TestCellUpdateHeight.TestTableViewCell:0x7fa1d208a000.bottom - 15.0>",
"<NSLayoutConstraint:0x6080002819f0 'UIView-Encapsulated-Layout-Height' TestCellUpdateHeight.TestTableViewCell:0x7fa1d208a000'TestTableViewCell'.height == 230 (active)>"
)
Will attempt to recover by breaking constraint
In general, to update the height constraint of a uiview:UIView you should save it first:
var viewHeightConstraint: Constraint!
uiview.snp.makeConstraints { (make) in
viewHeightConstraint = make.height.equalTo(50).constraint
}
If you simply use updateConstraints function, it will add a new height constraint that causes the issue Unable to simultaneously satisfy constraints. So you have to remove the last one:
viewHeightConstraint.deactivate()
Then make constraint again:
uiview.snp.makeConstraints { (make) in
viewHeightConstraint = make.height.equalTo(100).constraint
}
You cannot update cell's height just by changing its constraint.
Table can only update the height of its cells as a result of reloadData() call, after which it will ask its delegate for cell's height (or calculate automatically, if your cells are self-sizing).
So, to get the effect you want you might do something like the following.
In buttonBClicked method remember the state you want to get (using some variable maybe).
In table delegate's method tableView(_:, heightForRowAt:) return the correct height for the cell.
This is not ideal and serves just as a direction for considering your solution. My main point is that you need to reload table view to change cell's height.
What you currently do
labelA.snp.updateConstraints { (make) in
make.bottom.equalTo(buttonC.snp.top).offset(-100)
}
will increase the bottom distance of the labelA , but will leave it's top constant the same you need to either
1- Update the height of the labelA
or
2- Update the height of the redView in front of it
Also don't forget to call
cell.cellContainView.updateConstrain(sender: sender)
cell.layoutIfNeeded()
note also because of cell reusing you may find other cell stretched , so you need to keep track of stretched cell indices and apply that inside cellForRowAt
You can also do this
func tableView(_ tableView: UITableView,
heightForRowAt indexPath: IndexPath) -> CGFloat
return expandArr[indexPath.row] ? 300 : 100
}
where
var expandArr = [Bool]()
indicating whether the cell is expanded or not , also if you have a model you may add a bool value to it instead of this separate arr ( it's for illustration )
If you need recalculate height cell (without recreate cells / reload cells) just call:
tableView.beginUpdates()
tableView.endUpdates()
i think you don’t need to change Bottom Constraint.what you required is Apply height Constraint to redView.and change it according to your button Selection.
func updateConstrain(sender: UIButton) {
switch sender {
case buttonA:
redView.snp.updateConstraints { (make) in
make.heigh.equalTo(10)
}
case buttonB:
redView.snp.updateConstraints { (make) in
make.heigh.equalTo(100)
}
default:
break
}
}
}
And don’t forget to reload Specific Row after updating Constraint
#objc func buttonAClicked(sender: UIButton) {
let index = IndexPath(row: 0, section: 0)
let cell = tableView.cellForRow(at: index) as! TestTableViewCell
cell.cellContainView.updateConstrain(sender: sender)
yourtableview.reloadRows(at: [IndexPath(row: 0, section: 0)], with: UITableViewRowAnimation.none)
}
#objc func buttonBClicked(sender: UIButton) {
let index = IndexPath(row: 0, section: 0)
let cell = tableView.cellForRow(at: index) as! TestTableViewCell
cell.cellContainView.updateConstrain(sender: sender)
yourtableview.reloadRows(at: [IndexPath(row: 0, section: 0)], with: UITableViewRowAnimation.none)
}

Designing a UITableView/Cell - iOS

I'm designing a UITableView using subviews to populate the reusable cell of it, and I wish some opinion about that.
As I had tested, it works well. But, I don't know if it is a good solution.
The scenario is: I have a tableview with different kind of cells (layouts). When I was designing, it grows fast (my controller code), as I had to register a lot of cell and handle cellForRow. Then I come with that idea, to instantiate different subviews for one unique reusable cell and use a 'Presenter' to handle delegate/datasource. You think is that a problem? And is that a good approach?
Thanks in advance!
Ps.: sorry for any english error!
EDITED:
Here is the session in project followed by de codes:
Codes at:
OrderDetailCell
class OrderDetailCell: UITableViewCell {
//MARK: Outlets
#IBOutlet weak var cellHeight: NSLayoutConstraint!
#IBOutlet weak var viewContent: UIView!
//Variables
var didUpdateLayout = false
internal func setupLayoutWith(view: UIView){
cellHeight.constant = view.frame.height
viewContent.frame = view.frame
viewContent.addSubview(view)
updateConstraints()
layoutIfNeeded()
didUpdateLayout = true
}
}
OrderDetailSubview
class OrderDetailSubview: UIView {
var type: OrderDetailsSubViewType?
var height: CGFloat = 1
class func instanceFromNib(withType type: OrderDetailsSubViewType) -> OrderDetailSubview {
let view = UINib(nibName: type.rawValue, bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! OrderDetailSubview
switch type {
case .OrderDetailSubviewStatus:
view.height = 258
case .OrderDetailSubViewItem:
view.height = 129
case .OrderDetailSubViewStoreInformation:
view.height = 317
case .OrderDetailSubViewEvaluation:
view.height = 150
}
view.updateConstraints()
view.layoutIfNeeded()
return view
}
}
OrderDetailPresenter
enum OrderDetailsSubViewType: String {
case OrderDetailSubviewStatus = "OrderDetailSubviewStatus",
OrderDetailSubViewItem = "OrderDetailSubViewItem",
OrderDetailSubViewStoreInformation = "OrderDetailSubViewStoreInformation",
OrderDetailSubViewEvaluation = "OrderDetailSubViewEvaluation"
static let types = [OrderDetailSubviewStatus, OrderDetailSubViewItem, OrderDetailSubViewStoreInformation, OrderDetailSubViewEvaluation]
}
class OrderDetailPresenter {
//Constants
let numberOfSections = 4
//Variables
// var order: Order?
func setup(reusableCell: UITableViewCell, forRowInSection section: Int) -> OrderDetailCell {
let cell = reusableCell as! OrderDetailCell
for sub in cell.viewContent.subviews {
sub.removeFromSuperview()
}
let subView = OrderDetailSubview.instanceFromNib(withType: OrderDetailsSubViewType.types[section])
cell.setupLayoutWith(view: subView)
return cell
}
func numberOfRowsForSection(_ section: Int) -> Int {
switch section {
case 1:
//TODO: count de offerList
return 4
default:
return 1
}
}
}
OrderDetailViewController
class OrderDetailViewController: BaseViewController {
//MARK: Outlets
#IBOutlet weak var tableView: UITableView!
var presenter = OrderDetailPresenter()
override func setupView() {
setupTableView()
}
}
extension OrderDetailViewController: UITableViewDataSource, UITableViewDelegate {
internal func setupTableView() {
tableView.delegate = self
tableView.dataSource = self
tableView.estimatedRowHeight = 600
tableView.rowHeight = UITableViewAutomaticDimension
tableView.register(UINib(nibName: "OrderDetailCell", bundle: nil), forCellReuseIdentifier: "OrderDetailCell")
}
func numberOfSections(in tableView: UITableView) -> Int {
return presenter.numberOfSections
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return presenter.numberOfRowsForSection(section)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let reusableCell = tableView.dequeueReusableCell(withIdentifier: "OrderDetailCell") as! OrderDetailCell
let cell = presenter.setup(reusableCell: reusableCell, forRowInSection: indexPath.section)
return cell
}
}
*Sorry for indentation here...
Thats it! What you think?
Here you want to have multiple UITableViewCell subclasses that implement the different layouts that you want, and then select the relevant one in you table view data source.
class Cell1: UITableViewCell {
let label = UILabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.contentView.addSubview(label)
}
... whatever other setup/layout you need to do in the class ...
}
class Cell2: UITableViewCell {
let imageView = UIImageView()
override init(style: UITableViewCellStyle, reuseIdentifier: String) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.contentView.addSubview(imageView)
}
... whatever other setup/layout you need to do in the class ...
}
Then in your view controller
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(Cell1.self, forCellReuseIdentifier: "cell1Identifier")
tableView.register(Cell2.self, forCellReuseIdentifier: "cell2Identifier")
}
...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row % 2 == 0 { // just alternating rows for example
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1Identifier", for: indexPath) as! Cell1
// set data on cell
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell2Identifier", for: indexPath) as! Cell2
// set data on cell
return cell
}
}
So this is just an example, but is using two different cell subclasses for alternating rows in the table view.
let dynamicCellID: String = "dynamicCellID" //One Cell ID for resuse
class dynamicCell: UITableViewCell {
var sub: UIView // you just need to specify the subview
init(sub: UIView) {
self.sub = sub
super.init(style: .default, reuseIdentifier: dynamicCellID)
self.addSubview(sub)
self.sub.frame = CGRect(x: 0, y: 0, width: sub.frame.width, height: sub.frame.height)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
And you need to create a views array the give that view to every cell in delegate
let views: [UIView] = []
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return views.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let v = views[indexPath.row]
return dynamicCell(sub: v)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let v = views[indexPath.row]
return v.frame.height + 10 //offset is 10 point
}

Resources