Add UILabels programmatically to a Collection Cell, swift - ios

I am trying to add UILabels in the subView of my Collection Cell.
But when I scroll to the other cell and come back all the UIlabels appear on both cells and some are written under the other..
I tried with collectionView.cellForItemAtIndexPath(indexPath) as? CollectionViewCell , but when I used it none UIlabel was displayed ( I tried with breaking points, it doesn't go after the if statement)
How can I fix it??
Thanks!!!
class CollectionView: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
var collection = [PFObject]()
#IBOutlet weak var collectionView: UICollectionView!
let sidePadding:CGFloat = 10
var checkLocation: Bool = false
override func viewDidLoad()
{
super.viewDidLoad();
self.collectionView!.delegate = self
self.collectionView!.dataSource = self
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.collection.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionCell", forIndexPath: indexPath) as! CollectionViewCell
cell.layer.borderColor = UIColor.lightGrayColor().CGColor
cell.layer.borderWidth = 0.5
cell.layer.cornerRadius = 3
let collectionViewWidth = self.collectionView.bounds.size.width - self.sidePadding * 2
cell.frame.size.width = collectionViewWidth
let collectionViewHeight = self.collectionView.bounds.size.height/4.5
cell.frame.size.height = collectionViewHeight
// Display the country name
if let value = self.collection[indexPath.row]["Name"] as? String {
cell.cellTitle.text = String(Int(indexPath.row)) + "." + value
}
let width = (cell.bounds.width - 94 - 4*3 - 60 - 20)/4
let cellheight = CGFloat(6)
let cellheight1 = CGFloat(6 + 12 + 2)
var array = [String]()
if let MWl = collection[indexPath.row]["MW"] as? Int
{
if MWl == 1 {
array.append("M")
} else if MWl == 2 {
array.append("M")
array.append("W")
}
}
if let JAl = collection[indexPath.row]["JA"] as? Int
{
if JAl == 1 {
array.append("Jy")
} else if JAl == 2 {
array.append("Jy")
array.append("Ac")
}
}
if let HK = collection[indexPath.row]["HK"] as? Int
{
if HK == 1 {
array.append("HB")
} else if HK == 2 {
array.append("HB")
array.append("Ks")
}
}
if let SSl = collection[indexPath.row]["SSl"] as? Int
{
if SSl == 1 {
array.append("AB")
} else if SSl == 2 {
array.append("AB")
array.append("CD")
}
//I tried here too
// if let myCell = collectionView.cellForItemAtIndexPath(indexPath) as? CollectionViewCell
if array.count <= 4 {
for i in 0..<array.count {
let taille = CGFloat(i)
var si = CGFloat((1+i)*3 + 94 + 30)
let label = UILabel() as UILabel
label.frame = CGRectMake((si + width*taille), cellheight, width, 12)
label.textColor = UIColor(red: 0/255, green: 125/255, blue: 255/255, alpha: 1.0)
label.backgroundColor = UIColor.clearColor()
label.layer.borderWidth = 0.7
label.layer.borderColor = UIColor.lightGrayColor().CGColor
label.font = UIFont(name: "Futura-Medium", size: 9)
label.textAlignment = NSTextAlignment.Center
label.numberOfLines = 1
label.text = array[i]
label.layer.masksToBounds = true
label.layer.cornerRadius = 3.5
if let myCell = collectionView.cellForItemAtIndexPath(indexPath) as? CollectionViewCell {
myCell.contentView.addSubview(label)
}
}
} else {
for i in 0...3 {
let taille = CGFloat(i)
var si = CGFloat((1+i)*3 + 94 + 30)
let label = UILabel() as UILabel
label.frame = CGRectMake((si + width*taille), cellheight, width, 12)
label.textColor = UIColor(red: 0/255, green: 125/255, blue: 255/255, alpha: 1.0)
label.backgroundColor = UIColor.clearColor()
label.layer.borderWidth = 0.7
label.layer.borderColor = UIColor.lightGrayColor().CGColor
label.font = UIFont(name: "Futura-Medium", size: 9)
label.textAlignment = NSTextAlignment.Center
label.numberOfLines = 1
label.text = array[i]
label.layer.masksToBounds = true
label.layer.cornerRadius = 3.5
if let myCell = collectionView.cellForItemAtIndexPath(indexPath) as? CollectionViewCell {
myCell.contentView.addSubview(label)
}
}
var j = 0 as Int
for i in 4..<array.count {
let taille = CGFloat(j)
let si = CGFloat((1+j)*3 + 94 + 30)
let label = UILabel() as UILabel
label.frame = CGRectMake((si + width*taille), cellheight1, width, 12)
label.textColor = UIColor(red: 0/255, green: 125/255, blue: 255/255, alpha: 1.0)
label.backgroundColor = UIColor.clearColor()
label.layer.borderWidth = 0.7
label.layer.borderColor = UIColor.lightGrayColor().CGColor
label.font = UIFont(name: "Futura-Medium", size: 9)
label.textAlignment = NSTextAlignment.Center
label.numberOfLines = 1
label.text = array[i]
label.layer.masksToBounds = true
label.layer.cornerRadius = 3.5
if let myCell = collectionView.cellForItemAtIndexPath(indexPath) as? CollectionViewCell {
myCell.contentView.addSubview(label)
}
j = j + 1
}
}
return cell
}
}
EDIT
I tried to create the UILabel programmatically. But in that way I used the elements designed with the StoryBoard and the elements created programmatically. And actually I can't because of this :
collectionView!.registerClass(RDCell.self, forCellWithReuseIdentifier: "Cell")
I create all the content of the cell programmatically ( the collectionView is created with the storyboard) and it works perfectly.

The cell is being reused, therefore you are always adding new labels each time cellForItemAtIndexPath is called. Just tag your labels like label.tag = 1 and when you dequeue the cell remove every subview with this tag, like
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionCell", forIndexPath: indexPath) as! CollectionViewCell
for view in cell.subviews {
if view.tag == 1 {
view.removeFromSuperview()
}
}
You will be always recreating the labels though, which is bad design. I suggest designing those labels on storyboard or if you insist on doing it in code keep optional references to the label in the cell to not recreate them each time cellForItemAtIndexPath is called.

not recommended but you can do is,
Add tag to each label like 1000 or something and find sub views of cell if any of subview tag matches with label tag remove that view
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionCell", forIndexPath: indexPath) as! CollectionViewCell
for let labelIs in cell.subviews
{
if labelIs.tag == 1000
{
labelIs.removeFromSuperview()
}
}
//some whare
var label = UILabel()
label.tag = 1000
return cell
}

Related

How to add constraints to a collection view cell once the cell is selected?

I am trying to create a feature programmatically so that when a user selects a cell in the collection view the app keeps a count of the image selected and adds it as an overlay. I am also wanting to add the video duration to the bottom of the image if the selection is a video. I know my problem is in my constraints. You can see in the image example below that I am trying to add the count to the top left of the collection view cell, but also when the user deselects a cell the count adjusts so for example if the number 2 in the image below was deselected the number 3 would become 2. For the most part I think I have the code working but I cannot get the constraints to work. With the current configuration I am getting an error (see below) but I do not even know where to begin with this problem.
"Unable to activate constraint with anchors because they have
no common ancestor. Does the constraint or its anchors reference
items in different view hierarchies? That's illegal."
CollectionView:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let cell = collectionView.cellForItem(at: indexPath) as? TestCVCell {
cell.commonInit()
}
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
if let cell = collectionView.cellForItem(at: indexPath) as? TestCVCell {
//Not sure what to put here
}
}
Overlay
class CustomAssetCellOverlay: UIView {
let countSize = CGSize(width: 40, height: 40)
lazy var circleView: UIView = {
let view = UIView()
view.backgroundColor = .black
view.layer.cornerRadius = self.countSize.width / 2
view.alpha = 0.4
return view
}()
let countLabel: UILabel = {
let label = UILabel()
let font = UIFont.preferredFont(forTextStyle: .headline)
label.font = UIFont.systemFont(ofSize: font.pointSize, weight: UIFont.Weight.bold)
label.textAlignment = .center
label.textColor = .white
label.adjustsFontSizeToFitWidth = true
return label
}()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
private func commonInit() {
addSubview(circleView)
addSubview(countLabel)
//***** START - UPDATED BASED ON SUGGESTION IN COMMENTS******
countLabel.translatesAutoresizingMaskIntoConstraints = false
//***** END - UPDATED BASED ON SUGGESTION IN COMMENTS******
countLabel.centerXAnchor.constraint(equalTo: circleView.centerXAnchor).isActive = true
countLabel.centerYAnchor.constraint(equalTo: circleView.centerYAnchor).isActive = true
}
}
Collection View Cell
var img = UIImageView()
var overlayView = UIView()
var asset: PHAsset? {
didSet {}
}
var isVideo: Bool = false {
didSet {
durationLabel.isHidden = !isVideo
}
}
override var isSelected: Bool {
didSet { overlay.isHidden = !isSelected }
}
var imageView: UIImageView = {
let view = UIImageView()
view.clipsToBounds = true
view.contentMode = .scaleAspectFill
view.backgroundColor = UIColor.gray
return view
}()
var count: Int = 0 {
didSet { overlay.countLabel.text = "\(count)" }
}
var duration: TimeInterval = 0 {
didSet {
let hour = Int(duration / 3600)
let min = Int((duration / 60).truncatingRemainder(dividingBy: 60))
let sec = Int(duration.truncatingRemainder(dividingBy: 60))
var durationString = hour > 0 ? "\(hour)" : ""
durationString.append(min > 0 ? "\(min):" : ":")
durationString.append(String(format: "%02d", sec))
durationLabel.text = durationString
}
}
let overlay: CustomAssetCellOverlay = {
let view = CustomAssetCellOverlay()
view.isHidden = true
return view
}()
let durationLabel: UILabel = {
let label = UILabel()
label.preferredMaxLayoutWidth = 80
label.backgroundColor = .gray
label.textColor = .white
label.textAlignment = .right
label.font = UIFont.boldSystemFont(ofSize: 20)
return label
}()
func commonInit() {
addSubview(imageView)
imageView.addSubview(overlay)
imageView.addSubview(durationLabel)
imageView.translatesAutoresizingMaskIntoConstraints = false
//***** START - UPDATED BASED ON SUGGESTION IN COMMENTS******
overlay.translatesAutoresizingMaskIntoConstraints = false
overlayView.translatesAutoresizingMaskIntoConstraints = false
//***** END - UPDATED BASED ON SUGGESTION IN COMMENTS******
NSLayoutConstraint.activate([
overlay.topAnchor.constraint(equalTo: imageView.topAnchor),
overlay.bottomAnchor.constraint(equalTo: imageView.bottomAnchor),
overlay.leftAnchor.constraint(equalTo: imageView.leftAnchor),
overlay.rightAnchor.constraint(equalTo: imageView.rightAnchor),
overlayView.centerXAnchor.constraint(equalTo: overlay.centerXAnchor),
overlayView.centerYAnchor.constraint(equalTo: overlay.centerYAnchor),
overlayView.widthAnchor.constraint(equalToConstant: 80.0),
overlayView.heightAnchor.constraint(equalToConstant: 80.0),
]
)
}
//Some other stuff

UITableView with custom cells lags while scrolling

My problem is that UITableView lags quite a lot while scrolling.
This is what I am trying to achieve
Starting from the top I have a simple section header with only one checkbox and one UILabel. Under this header, you can see a custom cell with only one UILabel aligned to the center. This custom cell works like another header for the data that would be shown below (Basically a 3D array). Under these "headers" are custom cells that contain one multiline UILabel and under this label is a container for a variable amount of lines containing a checkbox and an UILabel. On the right side of the cell is also a button (blue/white arrow).
So this means the content is shown like this:
Section header (containing day and date)
Custom UITableViewCell = header (containing some header information)
Custom UITableViewCell (containing data to be shown)
Here is my code:
cellForRowAt:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let (isHeader, headerNumber, semiResult) = checkIfIsHeader(section: indexPath.section, row: indexPath.row)
let row = indexPath.row
if isHeader {
let chod = objednavkaDny[indexPath.section].chody[headerNumber+1]
let cell = tableView.dequeueReusableCell(withIdentifier: cellHeaderReuseIdentifier, for: indexPath) as! ObjednavkyHeaderTableViewCell
cell.titleLabel.text = chod.popisPoradiJidla
cell.selectionStyle = .none
return cell
}else{
let chod = objednavkaDny[indexPath.section].chody[headerNumber]
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! ObjednavkyTableViewCell
cell.updateData(objednavka: chod.objednavky[row-semiResult], canSetAmount: self.typDialogu == 3)
return cell
}
}
checkIfIsHeader:
func checkIfIsHeader(section: Int, row: Int) -> (Bool, Int, Int){
if let cachedResult = checkIfHeaderCache[section]?[row] {
return (cachedResult[0] == 1, cachedResult[1], cachedResult[2])
}
var isHeader = false
var semiResult = 0
var headerNumber = -1
for (index, chod) in objednavkaDny[section].chody.enumerated() {
let sum = chod.objednavky.count
if row == semiResult {
isHeader = true
break
}else if row < semiResult {
semiResult -= objednavkaDny[section].chody[index-1].objednavky.count
break
}else {
headerNumber += 1
semiResult += 1
if index != objednavkaDny[section].chody.count - 1 {
semiResult += sum
}
}
}
checkIfHeaderCache[section] = [Int:[Int]]()
checkIfHeaderCache[section]![row] = [isHeader ? 1 : 0, headerNumber, semiResult]
return (isHeader, headerNumber, semiResult)
}
and the main cell that shows the data:
class ObjednavkyTableViewCell: UITableViewCell {
lazy var numberTextField: ObjednavkyTextField = {
let textField = ObjednavkyTextField()
textField.translatesAutoresizingMaskIntoConstraints = false
return textField
}()
let mealLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = .black
label.textAlignment = .left
label.font = UIFont(name: ".SFUIText", size: 15)
label.numberOfLines = 0
label.backgroundColor = .white
label.isOpaque = true
return label
}()
lazy var detailsButton: UIButton = {
let button = UIButton(type: .custom)
button.translatesAutoresizingMaskIntoConstraints = false
button.setImage(UIImage(named: "arrow-right")?.withRenderingMode(.alwaysTemplate), for: .normal)
button.imageView?.tintColor = UIColor.custom.blue.classicBlue
button.imageView?.contentMode = .scaleAspectFit
button.contentHorizontalAlignment = .right
button.imageEdgeInsets = UIEdgeInsetsMake(10, 0, 10, 0)
button.addTarget(self, action: #selector(detailsButtonPressed), for: .touchUpInside)
button.backgroundColor = .white
button.isOpaque = true
return button
}()
let pricesContainerView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .white
view.isOpaque = true
return view
}()
var canSetAmount = false {
didSet {
canSetAmount ? showNumberTextField() : hideNumberTextField()
}
}
var shouldShowPrices = false {
didSet {
shouldShowPrices ? showPricesContainerView() : hidePricesContainerView()
}
}
var pricesContainerHeight: CGFloat = 0
private let priceViewHeight: CGFloat = 30
var mealLabelLeadingConstraint: NSLayoutConstraint?
var mealLabelBottomConstraint: NSLayoutConstraint?
var pricesContainerViewHeightConstraint: NSLayoutConstraint?
var pricesContainerViewBottomConstraint: NSLayoutConstraint?
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
#objc func detailsButtonPressed() {
}
func updateData(objednavka: Objednavka, canSetAmount: Bool) {
self.canSetAmount = canSetAmount
if let popisJidla = objednavka.popisJidla, popisJidla != "", popisJidla != " " {
self.mealLabel.text = popisJidla
}else{
self.mealLabel.text = objednavka.nazevJidelnicku
}
if objednavka.objects.count > 1 {
shouldShowPrices = true
setPricesStackView(with: objednavka.objects)
checkIfSelected(objects: objednavka.objects)
}else{
shouldShowPrices = false
self.numberTextField.text = String(objednavka.objects[0].pocet)
//setSelected(objednavka.objects[0].pocet > 0, animated: false)
objednavka.objects[0].pocet > 0 ? setSelectedStyle() : setDeselectedStyle()
}
}
//---------------
func checkIfSelected(objects: [ObjednavkaObject]) {
var didChangeSelection = false
for object in objects { // Checks wether cell should be selected or not
if object.pocet > 0 {
setSelected(true, animated: false)
setSelectedStyle()
didChangeSelection = true
break
}
}
if !didChangeSelection {
setSelected(false, animated: false)
setDeselectedStyle()
}
}
//--------------
func showNumberTextField() {
numberTextField.isHidden = false
mealLabelLeadingConstraint?.isActive = false
mealLabelLeadingConstraint = mealLabel.leadingAnchor.constraint(equalTo: numberTextField.trailingAnchor, constant: 10)
mealLabelLeadingConstraint?.isActive = true
}
func hideNumberTextField() {
numberTextField.isHidden = true
mealLabelLeadingConstraint?.isActive = false
mealLabelLeadingConstraint = mealLabel.leadingAnchor.constraint(equalTo: readableContentGuide.leadingAnchor, constant: 0)
mealLabelLeadingConstraint?.isActive = true
}
func showPricesContainerView() {
hideNumberTextField()
pricesContainerView.isHidden = false
mealLabelBottomConstraint?.isActive = false
pricesContainerViewBottomConstraint?.isActive = true
}
func hidePricesContainerView() {
pricesContainerView.isHidden = true
pricesContainerViewBottomConstraint?.isActive = false
mealLabelBottomConstraint?.isActive = true
}
//--------------
func setSelectedStyle() {
self.backgroundColor = UIColor.custom.blue.classicBlue
mealLabel.textColor = .white
mealLabel.backgroundColor = UIColor.custom.blue.classicBlue
for subview in pricesContainerView.subviews where subview is ObjednavkyPriceView {
let priceView = (subview as! ObjednavkyPriceView)
priceView.titleLabel.textColor = .white
priceView.checkBox.backgroundColor = UIColor.custom.blue.classicBlue
priceView.titleLabel.backgroundColor = UIColor.custom.blue.classicBlue
priceView.backgroundColor = UIColor.custom.blue.classicBlue
}
pricesContainerView.backgroundColor = UIColor.custom.blue.classicBlue
detailsButton.imageView?.tintColor = .white
detailsButton.backgroundColor = UIColor.custom.blue.classicBlue
}
func setDeselectedStyle() {
self.backgroundColor = .white
mealLabel.textColor = .black
mealLabel.backgroundColor = .white
for subview in pricesContainerView.subviews where subview is ObjednavkyPriceView {
let priceView = (subview as! ObjednavkyPriceView)
priceView.titleLabel.textColor = .black
priceView.checkBox.backgroundColor = .white
priceView.titleLabel.backgroundColor = .white
priceView.backgroundColor = .white
}
pricesContainerView.backgroundColor = .white
detailsButton.imageView?.tintColor = UIColor.custom.blue.classicBlue
detailsButton.backgroundColor = .white
}
//-----------------
func setPricesStackView(with objects: [ObjednavkaObject]) {
let subviews = pricesContainerView.subviews
var subviewsToDelete = subviews.count
for (index, object) in objects.enumerated() {
subviewsToDelete -= 1
if subviews.count - 1 >= index {
let priceView = subviews[index] as! ObjednavkyPriceView
priceView.titleLabel.text = object.popisProduktu // + " " + NSNumber(value: object.cena).getFormattedString(currencySymbol: "Kč") // TODO: currencySymbol
priceView.canSetAmount = canSetAmount
priceView.count = object.pocet
priceView.canOrder = (object.nelzeObj == nil || object.nelzeObj == "")
}else {
let priceView = ObjednavkyPriceView(frame: CGRect(x: 0, y: CGFloat(index) * priceViewHeight + CGFloat(index * 5), width: pricesContainerView.frame.width, height: priceViewHeight))
pricesContainerView.addSubview(priceView)
priceView.titleLabel.text = object.popisProduktu // + " " + NSNumber(value: object.cena).getFormattedString(currencySymbol: "Kč") // TODO: currencySymbol
priceView.numberTextField.delegate = self
priceView.canSetAmount = canSetAmount
priceView.canOrder = (object.nelzeObj == nil || object.nelzeObj == "")
priceView.count = object.pocet
pricesContainerHeight += ((index == 0) ? 30 : 35)
}
}
if subviewsToDelete > 0 { // Deletes unwanted subviews
for _ in 0..<subviewsToDelete {
pricesContainerView.subviews.last?.removeFromSuperview()
pricesContainerHeight -= pricesContainerHeight + 5
}
}
if pricesContainerHeight < 0 {
pricesContainerHeight = 0
}
pricesContainerViewHeightConstraint?.constant = pricesContainerHeight
}
func setupView() {
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.main.scale
self.backgroundColor = .white
contentView.addSubview(numberTextField)
contentView.addSubview(mealLabel)
contentView.addSubview(detailsButton)
contentView.addSubview(pricesContainerView)
setupConstraints()
}
func setupConstraints() {
numberTextField.anchor(leading: readableContentGuide.leadingAnchor, size: CGSize(width: 30, height: 30))
numberTextField.centerYAnchor.constraint(equalTo: mealLabel.centerYAnchor).isActive = true
detailsButton.anchor(trailing: readableContentGuide.trailingAnchor, size: CGSize(width: 30, height: 30))
detailsButton.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
mealLabel.anchor(top: contentView.topAnchor, trailing: detailsButton.leadingAnchor, padding: .init(top: 10, left: 0, bottom: 0, right: -10))
mealLabelBottomConstraint = mealLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10)
mealLabelBottomConstraint?.priority = UILayoutPriority(rawValue: 999)
pricesContainerView.anchor(top: mealLabel.bottomAnchor, leading: readableContentGuide.leadingAnchor, trailing: detailsButton.leadingAnchor, padding: .init(top: 10, left: 0, bottom: 0, right: -10))
pricesContainerViewBottomConstraint = pricesContainerView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10)
pricesContainerViewBottomConstraint?.priority = UILayoutPriority(rawValue: 999)
pricesContainerViewHeightConstraint = pricesContainerView.heightAnchor.constraint(equalToConstant: 0)
pricesContainerViewHeightConstraint?.priority = UILayoutPriority(rawValue: 999)
pricesContainerViewHeightConstraint?.isActive = true
}
}
To conclude how it is done:
tableView.rowHeight is set to UITableViewAutomaticDymension
inside cellForRowAt I get the data from an array and give it to the
cell
all the cells are set up in code using constraints
all the views have set isOpaque = true
heights of the cells are cached
cells are set to rasterize
I also noticed that it lags at certain scroll levels and that sometimes it works just fine and sometimes it lags a lot.
Despite all of the optimization I have done, the tableView still lags while scrolling.
Here is a screenshot from Instruments
Any tip how to improve the scrolling performance is highly appreciated!
(I might have forgotten to include some code/information so feel free to ask me in the comments.)
I can't tell you where the lag happens exactly but when we are talking about lagging during scrolling, it's related to your cellForRowAt delegate method. What happends is that too many things are going on within this method and it's called for every cells that are displaying & going to display. I see that your are trying to cache the result by checkIfHeaderCache but still, there is a for loop at the very beginning to determine header cell.
Suggestions:
I don't know where you get data (objednavkaDny) from but right after you get the data, do a full loop through and determin cell type one by one, and save the result some where base on your design. During this loading time, you can show some loading message on the screen. Then, within the cellForRow method, you should be just simply using things like
if (isHeader) {
render header cell
} else {
render other cell
}
Bottom line:
cellForRow method is not designed to handle heavy calculations, and it will slow down the scrolling if you do so. This method is for assigning values to the cached table view cell only and that's the only thing it is good at.

How to add data for particular index in uitableview swift 3

I am creating a dynamic uilabel in CellforRowat for particuklar index i.e indexpath.row=0
But When I Scroll down I am seeing that UI Label on 4th Index as well ....
Why is it coming on 3rd index if I have already added a condition in Cellforroat as:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// var cell:ActivityMainTableViewCell?
if(CheckFlag == false){
//CheckFlag = true
}
else{
CheckFlag = false
}
// cell = tableView.dequeueReusableCell(withIdentifier: "Cell")! as? ActivityMainTableViewCell
let cell:ActivityMainTableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! ActivityMainTableViewCell
/// let cell = tableView.cellForRow(at: indexPath) as! ActivityMainTableViewCell
///let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ActivityMainTableViewCell
/// cell.viewheight.constant = 0
cell.imgViewFirst.layer.cornerRadius = (cell.imgViewFirst.frame.size.width) / 2
cell.imgViewFirst.layer.borderWidth = 3.0
cell.imgViewFirst.layer.borderColor = UIColor.white.cgColor
cell.imgViewFirst.clipsToBounds = true
cell.ImageViewThird.layer.cornerRadius = (cell.ImageViewThird.frame.size.width) / 2
cell.ImageViewThird.layer.borderWidth = 3.0
cell.ImageViewThird.layer.borderColor = UIColor.white.cgColor
cell.ImageViewThird.clipsToBounds = true
cell.ImageViewSecond.layer.cornerRadius = (cell.ImageViewSecond.frame.size.width) / 2
cell.ImageViewSecond.layer.borderWidth = 3.0
cell.ImageViewSecond.layer.borderColor = UIColor.white.cgColor
cell.ImageViewSecond.clipsToBounds = true
print(indexPath)
print(indexPath.row)
print(dicArray)
cell.DateOfMeeting.text = dicArray[indexPath.row]["Date"] as? String
cell.CompanyInMeetiong.text = dicArray[indexPath.row]["Company"] as? String
cell.lblNews.text = dicArray[indexPath.row]["News"] as? String
cell.lblCommonKey.text = dicArray[indexPath.row]["CommonKey"] as? String
print(SectordicArray)
cell.imgViewFirst.isHidden = true
cell.lblCommonKey.isHidden = true
cell.btnOthers.tag = indexPath.row
//for i in 0..<section.count {
print(cell.lblCommonKey.text)
print(indexPath.row)
RowHeight = 110.0
CellHeight = 140.0
isFirstTime = true
// print(AllCompanydicArray)
if(indexPath.row == 0){
let Data = AllCompanydicArray[indexPath.row]
print(Data)
for i in 0..<Data.count {
print(Data[i])
if(isFirstTime == false){
RowHeight = RowHeight + 30.0
CellHeight = CellHeight + 30.0
}
else{
isFirstTime = false
}
let Company = (Data[i] as NSDictionary).value(forKey: "Company") as! [String]
let Contacts = (Data[i] as NSDictionary).value(forKey: "Participants") as! [String]
// section.append(Company)
//items.append(Contacts)
for k in 0..<Company.count {
let newLabel = UILabel(frame: CGRect(x: 10.0, y: RowHeight, width:cell.frame.width, height: 30.0))
newLabel.text = Company[k]
newLabel.font = UIFont(name:"HelveticaNeue-Bold", size: 13)
cell.addSubview(newLabel)
}
for j in 0..<Contacts.count {
RowHeight = RowHeight + 30.0
CellHeight = CellHeight + 30.0
var
newLabel = UILabel(frame: CGRect(x: 10.0, y: RowHeight, width:30, height: 30.0))
newLabel.text = CaptionName(Name: Contacts[j])
//"RC"
newLabel.font = UIFont(name:"HelveticaNeue-Bold", size: 11)
newLabel.textAlignment = .center
newLabel.backgroundColor = getColorByHex(rgbHexValue: 0x002366, alpha: 0.9)// UIColor(red: 0.0, green: 14.0, blue: 40.0, alpha: 100.0)
newLabel.layer.cornerRadius = (newLabel.frame.size.width) / 2
newLabel.layer.borderWidth = 1.0
newLabel.clipsToBounds = true
newLabel.textColor = UIColor.white
newLabel.layer.borderColor = UIColor.white.cgColor
cell.addSubview(newLabel)
newLabel = UILabel(frame: CGRect(x: 50, y: RowHeight, width:cell.frame.width-30, height: 30.0))
newLabel.text = Contacts[j]//"Raghav Chopra"
newLabel.font = UIFont(name:"HelveticaNeue", size: 12)
cell.addSubview(newLabel)
}
}
}
else{
}
return cell
}
Please let me know how can i avoid uilabel on 4th index.

iOS Swift TableviewCell issue

I have a strange problem with tableView cell.
when I scroll tableView and cell disappear and back again to the cell I understand that tableView add similar cell exactly on cell.
for example look at the picture . 3 exact text add on each other.
cellForRowAtIndexPath function :
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
if indexPath.row == 0 {
let reviewNumber = UILabel()
if (self.book.review_count == 0) {
reviewNumber.text = "\(self.lang.book["no_review"]!)"
}
if (self.book.review_count > 0) {
reviewNumber.text = "\(self.book.review_count!) \(self.lang.general["review"]!)"
}
reviewNumber.textAlignment = .Right
reviewNumber.font = UIFont(name: "Vazir", size: 14)
reviewNumber.numberOfLines = 0
reviewNumber.translatesAutoresizingMaskIntoConstraints = false
reviewNumber.textColor = UIColor.grayColor()
cell.contentView.addSubview(reviewNumber)
let voteIcon = UIImageView()
voteIcon.image = UIImage(named: "vote-icn")
voteIcon.translatesAutoresizingMaskIntoConstraints = false
cell.contentView.addSubview(voteIcon)
cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[v0(24)]-|",options: [],metrics: nil,views: ["v0" : voteIcon]))
let reviewIcon = UIImageView()
reviewIcon.image = UIImage(named: "review-icn")
reviewIcon.translatesAutoresizingMaskIntoConstraints = false
cell.contentView.addSubview(reviewIcon)
cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[v0(24)]-|",options: [],metrics: nil,views: ["v0" : reviewIcon]))
let voteNumber = UILabel()
voteNumber.text = " ۴.۵ از ۱۶۵۴رأی"
voteNumber.textAlignment = .Left
voteNumber.font = UIFont(name: "Vazir", size: 14)
voteNumber.numberOfLines = 0
voteNumber.translatesAutoresizingMaskIntoConstraints = false
voteNumber.textColor = UIColor.grayColor()
cell.contentView.addSubview(voteNumber)
cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-3-[v0]-3-|",options: [],metrics: nil,views: ["v0" : reviewNumber]))
cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-3-[v0]-3-|",options: [],metrics: nil,views: ["v0" : voteNumber]))
cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-35-[v0]-8-[v1(25)]",options: [],metrics: nil,views: ["v0" : voteNumber, "v1" : voteIcon, "v2" : reviewNumber, "v3" : reviewIcon]))
cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[v2]-8-[v3(25)]-35-|",options: [],metrics: nil,views: ["v0" : voteNumber, "v1" : voteIcon, "v2" : reviewNumber, "v3" : reviewIcon]))
}
if indexPath.row == 1 {
let userBookStatusButtn = UIButton(type: .Custom)
userBookStatusButtn.setTitle("خواهم خواند", forState: .Normal)
userBookStatusButtn.alpha = 0.2
userBookStatusButtn.titleLabel?.font = UIFont(name: "Vazir", size: 14)
userBookStatusButtn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
// userBookStatusButtn.setImage(UIImage(named: "vote-icn"), forState: .Normal)
userBookStatusButtn.translatesAutoresizingMaskIntoConstraints = false
userBookStatusButtn.backgroundColor = UIColor(red:0.0/256.0 ,green:150.0/256.0, blue:136.0/256.0 ,alpha:1 )
cell.contentView.addSubview(userBookStatusButtn)
cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-20-[v0(48)]-20-|",options: [],metrics: nil,views: ["v0" : userBookStatusButtn]))
cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-35-[v0]-35-|",options: [],metrics: nil,views: ["v0" : userBookStatusButtn]))
}
if indexPath.row == 2 {
let topBorder = UIView()
topBorder.translatesAutoresizingMaskIntoConstraints = false
topBorder.backgroundColor = UIColor(white: 0.5, alpha: 0.5)
cell.contentView.addSubview(topBorder)
let bottomBorder = UIView()
bottomBorder.translatesAutoresizingMaskIntoConstraints = false
bottomBorder.backgroundColor = UIColor(white: 0.5, alpha: 0.5)
cell.contentView.addSubview(bottomBorder)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 5
paragraphStyle.baseWritingDirection = .RightToLeft
guard let descriptionStr = self.book.description else {return cell}
let attrString = NSMutableAttributedString(string: descriptionStr)
attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
let description = UILabel()
description.attributedText = attrString
description.textAlignment = .Justified
description.font = UIFont(name: "Vazir", size: 14)
description.numberOfLines = 0
description.translatesAutoresizingMaskIntoConstraints = false
description.lineBreakMode = NSLineBreakMode.ByWordWrapping
cell.contentView.addSubview(description)
let title = UILabel()
title.text = "\(self.lang.book["summery"]!)"
title.alpha = 0.2
title.textAlignment = .Center
title.font = UIFont(name: "Vazir-Bold", size: 16)
title.translatesAutoresizingMaskIntoConstraints = false
cell.contentView.addSubview(title)
cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[v0]-|",options: [.AlignAllCenterX],metrics: nil,views: ["v0" : title]))
cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-20-[v0]-20-|",options: [],metrics: nil,views: ["v0" : description]))
cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-8-[v1]-44-[v0]",options: [],metrics: nil,views: ["v0" : description,"v1" : title ]))
cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[v0]-8-|",options: [],metrics: nil,views: ["v0" : description,"v1" : title ]))
}
cell.textLabel?.text = nil
return cell
}
I get data from son file with Alamofire and reloadData :
func tableRefresh()
{
dispatch_async(dispatch_get_main_queue(), {
self.bookDetailTableView.reloadData()
})
}
what's my problem?
thanks guys.
You made a classical error when using iOS cells.
(I am a teacher, so I see this kind of error frequently... don't worry..)
some Considerations:
1) NEVER add a label to a cell. Doing so, very time a cell is reused, previous label stays here, and a new label is added
2) as label are transparent, you will see all text overlapped..
3) You are leaking memory, as no one will detach/ release labels.
so the way can be:
A)Simple for simple case
use TAGS, as Apple did on old days of cells..
(code i
make some defines:
let TEXT_TAG = 2000
add label if not present, if present get it vi TAG:
let cell = tableView.dequeueReusableCell(withIdentifier: REUSE, for: indexPath )
let text = "my text..."
if let label = cell.viewWithTag(TEXT_TAG) as? UILabel{
label.text = text
}else{
let frame = CGRect(x: 100, y: 20, width: 50, height: 50)
let label = UILabel(frame: frame)
label.text = text
cell.addSubview(label)
}
B) make a custom cell...
class CustomViewCell: UITableViewCell {
var label: UILabel?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let frame = CGRect(x: 100, y: 20, width: 50, height: 50)
let label = UILabel(frame: frame)
self.addSubview(label)
}
in controller simply:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: REUSE,
for: indexPath ) as! CustomViewCell
cell.label = "my text"
I get your problem,you get the cell from tableView reuseable pool.The first problem,if you want change UITableViewCell View,you need to creat a son class of it.I get a function to fix it.
I use Stackoverflow first time,I don't know where can I put my code,so I write it under this sentence.
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
for let item in cell.contentView.subviews {
item.removeFromSuperView();
}
And then using your code,it should help you.

how can I display the following scenes hierarchy in swift using collectionView?

I have the following display scenes available. I am getting confused what type of hierarchy of controls I should take to display these type of view in xib .
please give ideas to show these types of scenes. because my items are coming dynamically . Its not fixed. so if I took tableview to display the first items and its categories then where should i display the rest items.
Edited
I took four sections. In 1st section collection and delivery buttons. In 3rd notes and in 4th allergy & checkout .
In 2nd my order items are there. but here I have two level of data.. order item name like chicken kabab small,... etc and 2nd level its addons like plain nan, bottle of drink,... etc. Here my order items is iterating in cell as well as my addons are iterating. I took the order items name in cell. now where should i take the addon items programatically and how to set the size of each cell based on its all contents inside it.
class cartVC: UIViewController ,UITableViewDataSource,UITableViewDelegate,UITextViewDelegate{
var tableData = ["al","dbd","gdge","kjdkas","al","dbd","gdge","kjdkas","al","dbd","gdge","kjdkas","al","dbd","gdge","kjdkas"]
var mainview = UIView()
#IBOutlet weak var cartTableView: UITableView!
#IBAction func backBtn(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func changeColor(sender:UISegmentedControl){
switch(sender.selectedSegmentIndex){
case 0:
print("collection clicked")
case 1:
print("delivery clicked")
default:
self.view.backgroundColor = UIColor.blueColor()
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 4
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rowcount = 0
if section == 0{
rowcount = 0
}
if section == 1 {
rowcount = tableData.count
}
if section == 2{
rowcount == 0
}
if section == 3{
rowcount == 0
}
return rowcount
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == 0{
let headerView = UIView()
//set the frame
let frame = UIScreen.mainScreen().bounds
// headerView.frame = CGRectMake(0, 0, tableView.frame.size.width, 60)
headerView.frame = CGRectMake(frame.minX , frame.minY, frame.width, 60)
headerView.backgroundColor = UIColor.whiteColor()
//Initialize segment control
let items = ["Collection","Delivery"]
let customSC = UISegmentedControl(items: items)
customSC.selectedSegmentIndex = 0
//set the frame amd segmented control
customSC.frame = CGRectMake(frame.minX + 10, frame.minY + 5, frame.width - 20, 30)
// style the segmented control
customSC.layer.cornerRadius = 5.0
customSC.backgroundColor = UIColor.clearColor()
customSC.tintColor = UIColor.redColor()
//add target action method
customSC.addTarget(self, action: #selector(CartViewController.changeColor(_:)), forControlEvents: .ValueChanged)
//add subview
headerView.addSubview(customSC)
//Add label
let headinglbl = UILabel(frame: CGRect(x: frame.minX + 10, y: frame.minY + 40, width: tableView.frame.size.width, height: 20))
headinglbl.text = "Your Order"
headinglbl.font = UIFont.boldSystemFontOfSize(17)
headinglbl.textColor = UIColor.blackColor()
headinglbl.textAlignment = .Center
headerView.addSubview(headinglbl)
mainview = headerView
}
if section == 2{
let totalView = UIView()
totalView.frame = CGRectMake(0, 0, tableView.frame.size.width, 60)
totalView.backgroundColor = UIColor.clearColor()
//Add discount label
let discount = 14.5
let discountlbl = UILabel(frame: CGRectMake(10, 0, tableView.frame.size.width, 20))
discountlbl.text = "Online Collection Discount(\(discount)%)"
discountlbl.font = UIFont.systemFontOfSize(14)
discountlbl.textColor = UIColor.darkGrayColor()
discountlbl.textAlignment = .Left
totalView.addSubview(discountlbl)
//Add discount price
let discountprice = UILabel(frame: CGRectMake(tableView.frame.size.width-60, 0, tableView.frame.size.width, 20))
discountprice.text = "£ 1.27"
discountprice.font = UIFont.systemFontOfSize(14)
discountprice.textColor = UIColor.blackColor()
discountprice.textAlignment = .Left
totalView.addSubview(discountprice)
//Add label
let lbl = UILabel(frame: CGRectMake(10, 20, tableView.frame.size.width, 40))
lbl.text = "Total"
lbl.font = UIFont.boldSystemFontOfSize(20)
lbl.textColor = UIColor.blackColor()
lbl.textAlignment = .Left
totalView.addSubview(lbl)
//calculate amount label
let totalAmountLbl = UILabel(frame: CGRectMake(totalView.frame.width-70, 20, totalView.frame.width, 40))
totalAmountLbl.text = "£ 0.0"
totalAmountLbl.font = UIFont.boldSystemFontOfSize(20)
totalAmountLbl.textColor = UIColor.blackColor()
totalAmountLbl.textAlignment = .Left
totalView.addSubview(totalAmountLbl)
mainview = totalView
}
if section == 3{
let footerView = UIView()
footerView.frame = CGRectMake(0, 0, tableView.frame.size.width, 200)
footerView.backgroundColor = UIColor.clearColor()
//Add note label
let notelbl = UILabel(frame: CGRectMake(10, 10, tableView.frame.size.width, 20))
notelbl.text = "Leave a note"
notelbl.font = UIFont.boldSystemFontOfSize(17)
notelbl.textColor = UIColor.blackColor()
notelbl.textAlignment = .Left
footerView.addSubview(notelbl)
//Add a note textview
let noteTxt = UITextView()
noteTxt.frame = CGRectMake(10, 40, footerView.frame.width-20, 50)
noteTxt.backgroundColor = UIColor.lightGrayColor()
noteTxt.keyboardType = UIKeyboardType.Default
noteTxt.text = "e.g. Instructions about yout order"
noteTxt.textColor = UIColor.blackColor()
noteTxt.delegate = self
footerView.addSubview(noteTxt)
// Add allergy button
let allergyBtn = UIButton(type:.System)
allergyBtn.frame = CGRectMake(50, 100, 200, 20)
allergyBtn.setTitle("Do You have any allergy ?", forState: .Normal)
allergyBtn.setTitleColor(UIColor.redColor(), forState: .Normal)
allergyBtn.titleLabel?.font = UIFont(name: "", size: 10)
footerView.addSubview(allergyBtn)
// Add checkout button
let checkoutBtn = UIButton(type:.System)
checkoutBtn.frame = CGRectMake(100, 140, 100, 40)
checkoutBtn.setTitle("Check out", forState: .Normal)
checkoutBtn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
checkoutBtn.titleLabel?.font = UIFont(name: "", size: 10)
checkoutBtn.backgroundColor = UIColor.redColor()
checkoutBtn.layer.cornerRadius = 5
footerView.addSubview(checkoutBtn)
mainview = footerView
}
return mainview
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cartcell")! as! CartTableViewCell
cell.itemLabel.text = tableData[indexPath.row]
return cell
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
var heightCount:CGFloat = 0
if section == 0{
heightCount = 60.0
}
if section == 2{
heightCount = 60.0
}
if section == 3{
heightCount = 200.0
}
return heightCount
}
My customcell code
import UIKit
class CartTableViewCell: UITableViewCell {
let padding: CGFloat = 5
var background: UIView!
var itemLabel: UILabel!
var priceLabel: UILabel!
var deleteBtn:UIButton!
override func awakeFromNib() {
super.awakeFromNib()
backgroundColor = UIColor.clearColor()
selectionStyle = .None
background = UIView(frame: CGRectZero)
background.alpha = 0.6
contentView.addSubview(background)
deleteBtn = UIButton(frame: CGRectZero)
deleteBtn.setImage(UIImage(named: "deleteBin.png"), forState: .Normal)
contentView.addSubview(deleteBtn)
itemLabel = UILabel(frame: CGRectZero)
itemLabel.textAlignment = .Left
itemLabel.textColor = UIColor.whiteColor()
contentView.addSubview(itemLabel)
priceLabel = UILabel(frame: CGRectZero)
priceLabel.textAlignment = .Center
priceLabel.textColor = UIColor.whiteColor()
contentView.addSubview(priceLabel)
}
override func layoutSubviews() {
super.layoutSubviews()
background.frame = CGRectMake(0, padding, frame.width, frame.height-2 * padding)
deleteBtn.frame = CGRectMake(padding, (frame.height - 25)/2, 40, 25)
priceLabel.frame = CGRectMake(frame.width-100, padding, 100, frame.height - 2 * padding)
itemLabel.frame = CGRectMake(CGRectGetMaxX(deleteBtn.frame) + 10, 0, frame.width - priceLabel.frame.width - CGRectGetMaxX(deleteBtn.frame) + 10, frame.height)
}
}
As our mates already said about using tableview and sections, Here we gonna follow the same way.Since it is a broad topic to explain i'll give some hint and at last you can find link for demo project.
First add a tableview in your storyboard then add collection,Delivery & Your order objects as tableview header
Create a new class subclass of UITableviewcell with xib let's name it as Cell1.Now add delete icon, main dish label and price label,for sub items we gonna use another UITableview.
Now create another UITableviewcell with xib name it as Cell2, prepare that xib for sub items and their price.
In cell1 numberOfSectionsInTableView return number of main dish count and in numberOfRowsInSection return 1, Now load name of all main dishes in their respective label's
Upto now we having some number of section(depending on number of main items) each section having one UITableview.
Now we have to change height of tableview cell dynamically depending on SubItems count. so in heightForRowAtIndexPath i have added following lines
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let subItems = tableContainer![indexPath.section].valueForKey("additional_items") as! NSArray
var defaultCellHeight:CGFloat = 37//Consider 37 as height of cell without subitems
//Following for loop keeps on increasing defaultCellHeight depending on available count
for _ in subItems {
defaultCellHeight += 37
}
return defaultCellHeight + 20
}
Since it is hard to explain everything deeply i have provide code for heightForRowAtIndexPath.While looking into the demo project you'll understand everything
NOTE : Upto now we have loaded all main dishes details, and we have provided enough room for upcoming sub item's.
In Cell1 class add tableview delegate and datasource in awakeFromNib,add all datasource methods as required.set numberOfSectionsInTableView as 1 and numberOfRowsInSection as subitem count
That's it we have loaded tableview dynamically as per your requirement.
Now at last add discount, total, leave a note& Checkout objects in separate tableviewcell class an load it at last index.
Or add add all those objects inside a UIView and add it as Main tableview's footer.
NOTE : The above hints are just for reference, For better clarification of concept i have added a demo project's github repo.
RESULT :

Resources