Problems with complex UITableViewCell - ios

I'm trying to implement a custom complex UITableViewCell. My data source is relatively simple, but I could have some multiple elements.
class Element: NSObject {
var id: String
var titles: [String]
var value: String
init(id: String, titles: [String], value: String) {
self.id = id
self.titles = titles
self.value = value
}
}
I have an array of elements [Element] and, as you can see, for each element titles could have multiple string values. I must use the following layouts:
My first approach was to implement a dynamic UITableViewCell, trying to add content inside self.contentView at runtime. Everything is working, but it's not so fine and as you can see, reusability is not handled in the right way. Lag is terrible.
import UIKit
class ElementTableCell: UITableViewCell {
var titles: [String]!
var value: String!
var width: CGFloat!
var titleViewWidth: CGFloat!
var cellHeight: Int!
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:)")
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
}
func drawLayout() {
titleViewWidth = (width * 2)/3
cellHeight = 46 * titles.count
for i in 0 ..< titles.count {
let view = initTitleView(title: titles[i], width: titleViewWidth, yPosition: CGFloat(cellHeight * i))
self.contentView.addSubview(view)
}
self.contentView.addSubview(initButton())
}
func initTitleView(title: String, width: CGFloat, yPosition: CGFloat) -> UIView {
let titleView: UILabel = UILabel(frame:CGRect(x:0, y:Int(yPosition), width: Int(width), height: 45))
titleView.text = title
return titleView
}
func initButton(value: String) -> UIButton {
let button = UIButton(frame:CGRect(x: 0, y: 0, width: 70, height:34))
button.setTitle(value, for: .normal)
button.center.x = titleViewWidth + ((width * 1)/3)/2
button.center.y = CGFloat(cellHeight/2)
return priceButton
}
}
And the UITableView delegate method:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = ElementTableCell(style: .default, reuseIdentifier: "ElementTableCell")
cell.width = self.view.frame.size.width
cell.titles = elements[indexPath.row].titles
cel.value = elements[indexPath.row].value
cell.drawLayout()
return cell
}
Now I'm thinking about a total different approach, such as using a UITableView Section for each element in elements array and a UITableViewCell for each title in titles. It could work, but I'm concerned about the right button.
Do you have any suggestion or other approach to share?

I solved changing application UI logic in order to overcome the problem. Thank you all.

Here's some code you can play with. It should work just be creating a new UITableView in a Storyboard and assigning it to BoxedTableViewController in this file...
//
// BoxedTableViewController.swift
//
import UIKit
class BoxedCell: UITableViewCell {
var theStackView: UIStackView!
var containingView: UIView!
var theButton: UIButton!
var brdColor = UIColor(white: 0.7, alpha: 1.0)
// "spacer" view is just a 1-pt tall UIView used as a horizontal-line between labels
// when there is more than one title label
func getSpacer() -> UIView {
let newView = UIView(frame: CGRect(x: 0, y: 0, width: 40, height: 1))
newView.backgroundColor = brdColor
newView.translatesAutoresizingMaskIntoConstraints = false
newView.heightAnchor.constraint(equalToConstant: 1.0).isActive = true
return newView
}
// "label view" is a UIView containing on UILabel
// embedding the label in a view allows for convenient borders and insets
func getLabelView(text: String, position: Int) -> UIView {
let v = UIView()
v.translatesAutoresizingMaskIntoConstraints = false
let newLabel = UILabel()
newLabel.font = UIFont.systemFont(ofSize: 15.0)
newLabel.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
newLabel.textColor = .black
newLabel.layer.borderWidth = 1
newLabel.layer.borderColor = brdColor.cgColor
newLabel.numberOfLines = 0
newLabel.text = text
newLabel.translatesAutoresizingMaskIntoConstraints = false
v.addSubview(newLabel)
newLabel.leadingAnchor.constraint(equalTo: v.leadingAnchor, constant: 8.0).isActive = true
newLabel.trailingAnchor.constraint(equalTo: v.trailingAnchor, constant: -8.0).isActive = true
var iTop: CGFloat = 0.0
var iBot: CGFloat = 0.0
// the passed "position" tells me whether this label is:
// a Single Title only
// the first Title of more than one
// the last Title of more than one
// or a Title with a Title above and below
// so we can set up proper top/bottom padding
switch position {
case 0:
iTop = 16.0
iBot = 16.0
break
case 1:
iTop = 12.0
iBot = 8.0
break
case -1:
iTop = 8.0
iBot = 12.0
break
default:
iTop = 8.0
iBot = 8.0
break
}
newLabel.topAnchor.constraint(equalTo: v.topAnchor, constant: iTop).isActive = true
newLabel.bottomAnchor.constraint(equalTo: v.bottomAnchor, constant: -iBot).isActive = true
return v
}
func setupThisCell(rowNumber: Int) -> Void {
// if containingView is nil, it hasn't been created yet
// so, create it + Stack view + Button
// else
// don't create new ones
// This way, we don't keep adding more and more views to the cell on reuse
if containingView == nil {
containingView = UIView()
containingView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(containingView)
containingView.layer.borderWidth = 1
containingView.layer.borderColor = brdColor.cgColor
containingView.backgroundColor = .white
containingView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 8.0).isActive = true
containingView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -8.0).isActive = true
containingView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 6.0).isActive = true
containingView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -6.0).isActive = true
theStackView = UIStackView()
theStackView.translatesAutoresizingMaskIntoConstraints = false
containingView.addSubview(theStackView)
theStackView.axis = .vertical
theStackView.spacing = 4.0
theStackView.alignment = .fill
theStackView.distribution = .fill
theButton = UIButton(type: .custom)
theButton.translatesAutoresizingMaskIntoConstraints = false
containingView.addSubview(theButton)
theButton.backgroundColor = .blue
theButton.setTitleColor(.white, for: .normal)
theButton.setTitle("The Button", for: .normal)
theButton.setContentHuggingPriority(1000, for: .horizontal)
theButton.centerYAnchor.constraint(equalTo: containingView.centerYAnchor, constant: 0.0).isActive = true
theButton.trailingAnchor.constraint(equalTo: containingView.trailingAnchor, constant: -8.0).isActive = true
theStackView.topAnchor.constraint(equalTo: containingView.topAnchor, constant: 0.0).isActive = true
theStackView.bottomAnchor.constraint(equalTo: containingView.bottomAnchor, constant: 0.0).isActive = true
theStackView.leadingAnchor.constraint(equalTo: containingView.leadingAnchor, constant: 0.0).isActive = true
theStackView.trailingAnchor.constraint(equalTo: theButton.leadingAnchor, constant: -8.0).isActive = true
}
// remove all previously added Title labels and spacer views
for v in theStackView.arrangedSubviews {
v.removeFromSuperview()
}
// setup 1 to 5 Titles
let n = rowNumber % 5 + 1
// create new Title Label views and, if needed, spacer views
// and add them to the Stack view
if n == 1 {
let aLabel = getLabelView(text: "Only one title for row: \(rowNumber)", position: 0)
theStackView.addArrangedSubview(aLabel)
} else {
for i in 1..<n {
let aLabel = getLabelView(text: "Title number \(i)\n for row: \(rowNumber)", position: i)
theStackView.addArrangedSubview(aLabel)
let aSpacer = getSpacer()
theStackView.addArrangedSubview(aSpacer)
}
let aLabel = getLabelView(text: "Title number \(n)\n for row: \(rowNumber)", position: -1)
theStackView.addArrangedSubview(aLabel)
}
}
}
class BoxedTableViewController: UITableViewController {
let cellID = "boxedCell"
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(BoxedCell.self, forCellReuseIdentifier: cellID)
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1250
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! BoxedCell
// Configure the cell...
cell.setupThisCell(rowNumber: indexPath.row)
return cell
}
}
I'll check back if you run into any problems with it (gotta run, and haven't fully tested it yet -- and ran out of time to comment it - ugh).

You can also use tableview as tableviecell and adjust cell accordingly.

u need to layout cell in func layoutsubviews after set data to label and imageview;

Yes, split ElementTableCell to section with header and cells is much better approach. In this case you have no need to create constraints or dealing with complex manual layout. This would make your code simple and make scrolling smooth.
The button you use can be easily moved to the reusable header view
Is you still want to keep it in one complete cell, where is a way to draw manually the dynamic elements, such as titles and separators lines. Manually drawing is faster as usual. Or remove all views from cell.contentView each time you adding new. But this way is much more complicated.
Greate article about how to make UITableView appearence swmoth:
Perfect smooth scrolling in UITableViews

Related

How to add options menu on UIBarButtonItem in swift?

I am trying to add options menu over a UIBarButtonItem similar to what we see in android for material design. Similar to this
But I am stuck on how to add it over a UIBarButtonItem. Once clicked this menu should pop up anchored to that UIBarButtonItem and clicking outside should dismiss it. How to achieve the same?
class ABMenu: UIView {
private var items:[ABMenuItem] = []
private var tableView:UITableView!
override init(frame: CGRect) {
super.init(frame: frame)
}
convenience init(barButtonItem:UIBarButtonItem,items:[ABMenuItem]) {
self.init(frame: .zero)
self.items = items
self.commonInit(barButtonItem: barButtonItem)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
private func commonInit(barButtonItem:UIBarButtonItem){
self.frame = CGRect(x: 10, y: 20, width: 200, height: self.items.count * 40)
self.backgroundColor = .white
self.layer.cornerRadius = 5
self.layer.shadowColor = UIColor.gray.withAlphaComponent(0.7).cgColor
self.layer.shadowOffset = CGSize(width: -1.0, height: 1.0)
self.layer.shadowRadius = 0.8
self.layer.shadowOpacity = 0.5
tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints=false
tableView.backgroundColor = .clear
tableView.tableFooterView=UIView()
tableView.separatorStyle = .none
tableView.delegate = self
tableView.dataSource = self
tableView.register(ABMenuItemCell.self, forCellReuseIdentifier: "itemCell")
self.addSubview(tableView)
tableView.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
tableView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 0).isActive = true
tableView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 0).isActive = true
tableView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
}
}
extension ABMenu:UITableViewDelegate,UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "itemCell", for: indexPath) as! ABMenuItemCell
cell.setup(item:self.items[indexPath.row])
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.items[indexPath.row].onTap()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 40
}
}
class ABMenuItemCell:UITableViewCell {
private var itemLabel:UILabel!
func setup(item:ABMenuItem){
for view in self.contentView.subviews {
view.removeFromSuperview()
}
self.selectionStyle = .none
itemLabel = UILabel()
itemLabel.translatesAutoresizingMaskIntoConstraints=false
itemLabel.backgroundColor = .white
itemLabel.text = item.name
itemLabel.textColor = .black
itemLabel.font = .systemFont(ofSize: 15)
itemLabel.numberOfLines = 1
itemLabel.lineBreakMode = .byTruncatingMiddle
self.contentView.addSubview(itemLabel)
itemLabel.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 0).isActive = true
itemLabel.leftAnchor.constraint(equalTo: self.contentView.leftAnchor, constant: 10).isActive = true
itemLabel.rightAnchor.constraint(equalTo: self.contentView.rightAnchor, constant: -10).isActive = true
itemLabel.heightAnchor.constraint(equalToConstant: 40).isActive = true
}
}
struct ABMenuItem {
var name:String
var onTap:(()->Void)
}
Try creating a view for the menu, then setting the X and Y position relative to the button, and setting the view's layer.zPosition = 1
Below is an example of how this could be done. Note, I haven't tested this code yet. To implement clicking outside the menu to close it, you'll need to create a transparent view the size of the screen, positioned underneath the menu, add a UITapGestureRecognizer to it, and then link to an IBAction that removes the menu from the view.
// calculate location of menu
let openMenuButtonOrigin = openMenuButton.frame.origin
let menuWidth = 200
let menuHeight = 100
let menuX = openMenuButtonOrigin.x - menuWidth
let menuY = openMenuButtonOrigin.y + menuHeight
// create menu (this can be done in XIB/Storyboard file as well)
let menuView = UIView(frame: CGRect(x: menuX, y: menuY, width: menuWidth, height: menuHeight))
// create menu option
let shareOption = UILabel()
shareOption.text = "Share"
shareOption.topAnchor.constraint(equalTo: menuView).isActive = true
shareOption.bottomAnchor.constraint(equalTo: menuView).isActive = true
shareOption.leadingAnchor.constraint(equalTo: menuView).isActive = true
shareOption.trailingAnchor.constraint(equalTo: menuView).isActive = true
menuView.addSubview(shareOption)
// add menu to view
menuView.layer.zPosition = 1
view.addSubview(menuView)

TableView Cells not formatting correctly unless image is cached

I am having an issue with my tableview, where the cells don't orient correctly before an image is cached, and only once I return back to a page and my image is cached do they orient correctly. Here is an example of what I am talking about, the first image is when I first go to the page, and I have a function which stores images in an imagecache, and the second picture is when I return to that page after navigating somewhere else, and the images are cached.
Incorrectly Formatted:
Correctly Formatted:
I know it is a very subtle difference
with the way it looks
but I'd love to get that figured out and understand why this is happening
My cells constant height is 85, and here is the relevant code:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//Indexing part I left out dw about this
let cell = discountTableView.dequeueReusableCell(withIdentifier: self.discountCellId, for: indexPath) as! DiscountCell
cell.textLabel?.text = discount.retailerName
cell.detailTextLabel?.text = discount.matchedFirstName + " " + discount.matchedLastName
cell.profileImageView.image = UIImage.gif(name: "imageLoading")!
grabImageWithCache(discount.retailerImageLink) { (profilePic) in
cell.profileImageView.image = profilePic
}
//Adding second Image
cell.matchImageView.image = UIImage.gif(name: "imageLoading")!
grabImageWithCache(discount.matchedProfileImage) { (matchProfilepic) in
cell.matchImageView.image = matchProfilepic
}
//declare no selection style for cell (avoid gray highlight)
cell.selectionStyle = .none
//format the cell's curvature
cell.layer.cornerRadius = 38
return cell
}
**I am curious as to why the height of the cells seem to change when the image is cached, because the height is set to a constant number, so I have no idea why it is changing. When I print the height of the cells it says it is 85 both times as well...
UITableViewCell Class:
class DiscountCell: UITableViewCell {
override func layoutSubviews() {
super.layoutSubviews()
//vertical spacing between cells
let padding = UIEdgeInsets(top: 0, left: 0, bottom: 7, right: 0)
bounds = bounds.inset(by: padding)
textLabel?.frame = CGRect(x: 120, y: textLabel!.frame.origin.y-10, width: textLabel!.frame.width, height: textLabel!.frame.height)
detailTextLabel?.frame = CGRect(x: 120, y: detailTextLabel!.frame.origin.y, width: detailTextLabel!.frame.width, height: detailTextLabel!.frame.height)
//spacing between cells
let margins = UIEdgeInsets(top: 0, left: 0, bottom: 85, right: 0)
contentView.frame = contentView.frame.inset(by: margins)
}
//sets a placeholder imageview
let profileImageView: UIImageView = {
let imageView = UIImageView ()
imageView.image = UIImage(named: "failed")
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.layer.cornerRadius = 35
imageView.layer.masksToBounds = true
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.layer.borderWidth = 2
imageView.layer.borderColor = #colorLiteral(red: 0.9725490196, green: 0.9725490196, blue: 0.9725490196, alpha: 1)
return imageView
}()
//PlaceHolder imageview for match
let matchImageView:UIImageView = {
let imageView = UIImageView ()
imageView.image = UIImage(named: "failed")
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.layer.cornerRadius = 35
imageView.layer.masksToBounds = true
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
return imageView
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
addSubview(matchImageView)
addSubview(profileImageView)
//Setting Profile Pic anchors
profileImageView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 5).isActive = true
profileImageView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
profileImageView.widthAnchor.constraint(equalToConstant: 70).isActive = true
profileImageView.heightAnchor.constraint(equalToConstant: 70).isActive = true
//Setting Match Anchors
matchImageView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
matchImageView.widthAnchor.constraint(equalToConstant: 70).isActive = true
matchImageView.heightAnchor.constraint(equalToConstant: 70).isActive = true
matchImageView.leftAnchor.constraint(equalTo: profileImageView.leftAnchor,constant: 35).isActive = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
I believe I have narrowed in on the issue, I noticed that the spacing between the cells was inconsistent both times, so I think the issue is with these lines of code
//vertical spacing between cells
let padding = UIEdgeInsets(top: 0, left: 0, bottom: 7, right: 0)
bounds = bounds.inset(by: padding)
I am not sure what to do differently, as I watched tutorials saying to change the contentviews insets but when I do, it has no effect, and I see things saying iOS 11 changed the way you do this, but haven't been able to find how to actually go about fixing this.
Couple notes...
Not a good idea to modify a cell's bounds or its contentView. UIKit uses those for a lot of things (such as adjusting contents when implementing table editing).
Cell subviews should be added to the cell's contentView, not to the cell itself. Again, due to how table views rely on that hierarchy.
You can use UIView and UIImageView subclasses to handle the "rounding" for you. For example:
class RoundImageView: UIImageView {
override func layoutSubviews() {
layer.cornerRadius = bounds.size.height * 0.5
}
}
class RoundEndView: UIView {
override func layoutSubviews() {
layer.cornerRadius = bounds.size.height * 0.5
}
}
Here is a complete implementation:
class RoundImageView: UIImageView {
override func layoutSubviews() {
layer.cornerRadius = bounds.size.height * 0.5
}
}
class RoundEndView: UIView {
override func layoutSubviews() {
layer.cornerRadius = bounds.size.height * 0.5
}
}
class DiscountCell: UITableViewCell {
// "Holder" view... contains all other UI elements
// use RoundEndView so it handles the corner radius by itself
let holderView: RoundEndView = {
let v = RoundEndView()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .white
return v
}()
//sets a placeholder imageview
// use RoundImageView so it handles the corner radius by itself
let profileImageView: RoundImageView = {
let imageView = RoundImageView()
imageView.image = UIImage(named: "failed")
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.layer.masksToBounds = true
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.layer.borderWidth = 2
imageView.layer.borderColor = #colorLiteral(red: 0.9725490196, green: 0.9725490196, blue: 0.9725490196, alpha: 1)
return imageView
}()
//PlaceHolder imageview for match
// use RoundImageView so it handles the corner radius by itself
let matchImageView: RoundImageView = {
let imageView = RoundImageView()
imageView.image = UIImage(named: "failed")
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.layer.masksToBounds = true
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
return imageView
}()
let mainLabel: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.font = UIFont.systemFont(ofSize: 17.0, weight: .regular)
return v
}()
let subLabel: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.font = UIFont.systemFont(ofSize: 14.0, weight: .regular)
return v
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() -> Void {
backgroundColor = .clear
contentView.addSubview(holderView)
holderView.addSubview(matchImageView)
holderView.addSubview(profileImageView)
holderView.addSubview(mainLabel)
holderView.addSubview(subLabel)
NSLayoutConstraint.activate([
// holder view constraints Top 5 pts from contentView Top
holderView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 5.0),
// Leading 12 pts from contentView Leading
holderView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 12.0),
// Trailing 5 pts from contentView Trailing
holderView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -5.0),
// 5 pts from contentView Bottom (use lessThanOrEqualTo to avoid auto-layout warnings)
holderView.bottomAnchor.constraint(lessThanOrEqualTo: contentView.bottomAnchor, constant: -5.0),
//Setting Profile Pic anchors - Top and Leading 5 pts from Top and Leading of Holder view
profileImageView.topAnchor.constraint(equalTo: holderView.topAnchor, constant: 5),
profileImageView.leadingAnchor.constraint(equalTo: holderView.leadingAnchor, constant: 5),
// Botom 5 pts from contentView Bottom - this will determine the height of the Holder view
profileImageView.bottomAnchor.constraint(equalTo: holderView.bottomAnchor, constant: -5),
// width 70 pts, height equal to width (keeps it "round")
profileImageView.widthAnchor.constraint(equalToConstant: 70.0),
profileImageView.heightAnchor.constraint(equalTo: profileImageView.widthAnchor),
//Setting Match Pic Anchors - 35 pts from Profile Leading, centerY to Profile
matchImageView.leadingAnchor.constraint(equalTo: profileImageView.leadingAnchor, constant: 35),
matchImageView.centerYAnchor.constraint(equalTo: profileImageView.centerYAnchor, constant: 0.0),
// same width and height as Profile
matchImageView.widthAnchor.constraint(equalTo: profileImageView.widthAnchor),
matchImageView.heightAnchor.constraint(equalTo: profileImageView.heightAnchor),
//Setting Main Label Anchors - Top equal to Top of Match image
mainLabel.topAnchor.constraint(equalTo: matchImageView.topAnchor, constant: 0.0),
// Leading 12 pts from Match image Trailing
mainLabel.leadingAnchor.constraint(equalTo: matchImageView.trailingAnchor, constant: 12.0),
// prevent Trailing from going past holder view Trailing
mainLabel.trailingAnchor.constraint(equalTo: holderView.trailingAnchor, constant: -16.0),
//Setting Sub Label Anchors - Top 8 pts from Main label Bottom
subLabel.topAnchor.constraint(equalTo: mainLabel.bottomAnchor, constant: 8.0),
// Leading and Trailing equal to Main label Leading / Trailing
subLabel.leadingAnchor.constraint(equalTo: mainLabel.leadingAnchor, constant: 0.0),
subLabel.trailingAnchor.constraint(equalTo: mainLabel.trailingAnchor, constant: 0.0),
])
}
}
// example Discount object struct
struct Discount {
var retailerName: String = ""
var matchedFirstName: String = ""
var matchedLastName: String = ""
var matchedProfileImage: String = ""
var retailerImageLink: String = ""
}
class DiscountViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let discountTableView = UITableView()
let discountCellId = "dcID"
var myData: [Discount] = []
override func viewDidLoad() {
super.viewDidLoad()
// a little sample data
var d = Discount(retailerName: "Cup & Cone", matchedFirstName: "Kara", matchedLastName: "Tomlinson", matchedProfileImage: "pro1", retailerImageLink: "")
myData.append(d)
d = Discount(retailerName: "Cup & Cone", matchedFirstName: "Sophie", matchedLastName: "Turner", matchedProfileImage: "pro2", retailerImageLink: "")
myData.append(d)
d = Discount(retailerName: "Another Retailer", matchedFirstName: "WanaB3", matchedLastName: "Nerd", matchedProfileImage: "pro3", retailerImageLink: "")
myData.append(d)
discountTableView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(discountTableView)
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
discountTableView.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
discountTableView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
discountTableView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
discountTableView.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: -20.0),
])
view.backgroundColor = UIColor(red: 1.0, green: 0.9, blue: 0.7, alpha: 1.0)
discountTableView.backgroundColor = UIColor(red: 0.66, green: 0.66, blue: 0.9, alpha: 1.0)
discountTableView.separatorStyle = .none
discountTableView.delegate = self
discountTableView.dataSource = self
discountTableView.register(DiscountCell.self, forCellReuseIdentifier: discountCellId)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//Indexing part I left out dw about this
let discount = myData[indexPath.row]
let cell = discountTableView.dequeueReusableCell(withIdentifier: self.discountCellId, for: indexPath) as! DiscountCell
cell.mainLabel.text = discount.retailerName
cell.subLabel.text = discount.matchedFirstName + " " + discount.matchedLastName
// add first image
if let img = UIImage(named: "imageLoading") {
cell.profileImageView.image = img
}
// use your custom image funcs
//cell.profileImageView.image = UIImage.gif(name: "imageLoading")!
//grabImageWithCache(discount.retailerImageLink) { (profilePic) in
// cell.profileImageView.image = profilePic
//}
//Adding second Image
if let img = UIImage(named: discount.matchedProfileImage) {
cell.matchImageView.image = img
}
// use your custom image funcs
//cell.matchImageView.image = UIImage.gif(name: "imageLoading")!
//grabImageWithCache(discount.matchedProfileImage) { (matchProfilepic) in
// cell.matchImageView.image = matchProfilepic
//}
//declare no selection style for cell (avoid gray highlight)
cell.selectionStyle = .none
return cell
}
}
Results:
Your cells are a pill shape, which means you can achieve the same effect by doing cell.layer.cornerRadius = cell.frame.height / 2. Next you should use top and bottom constraints for your profileImageView so it forces the cell to have a certain padding instead of trying to create the padding yourself. The problem is that your cell height is changing a little bit when the images are cached, no idea what could be causing that.

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.

Add subview on tableView cells causes a sad patchwork

I want to give a chat aspect to a table view of messages in my iPhone app.
In order to perform a quality render I add two subviews: the text and the "container" which is just a view with background color.
Even if it works the first time, when I scroll, it becomes really messy because it keeps adding lots of subviews.
Here you can see it when clean
And then when it has become messy
Here is the function to handle the transform, it's called when scrolling.
func configChatCell(cell: UITableViewCell, text: String, color:UIColor)
{
cell.textLabel?.numberOfLines = 0
cell.textLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
cell.textLabel?.textColor = UIColor.whiteColor()
let fixedWidth = cell.bounds.width - 150
let textView: UITextView = UITextView(frame: CGRect(x: 0, y: 0, width: 10, height: CGFloat.max))
textView.text = text
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
var newFrame = textView.frame
newFrame.size = CGSize(width: min(newSize.width, fixedWidth), height: newSize.height)
textView.sizeThatFits(newFrame.size)
textView.frame = newFrame
textView.backgroundColor = UIColor.clearColor()
self.rowHeight = textView.frame.height+20
let view = UIView()
view.backgroundColor = color
print(textView.frame.height+10)
view.frame = CGRect(x: 0, y: 5, width: textView.frame.width+50, height: textView.frame.height+10)
view.layer.cornerRadius = 5
cell.backgroundColor = UIColor.clearColor()
cell.contentView.addSubview(view)
cell.contentView.addSubview(textView)
cell.contentView.sendSubviewToBack(view)
}
If I remove the subviews each time I scroll, nothing appears on screen.
Can somebody help me to find a solution? Or is there any other way to do this?
Thanks in advance!
I quickly wrote up something for this.
It starts with the ChatCell
class ChatCell: UITableViewCell {
var messageLabel: UILabel? {
didSet {
messageLabel?.text = message
}
}
var message: String? {
didSet {
messageLabel?.text = message
}
}
class func messageCell(withText text: String, leading: Bool = true) -> ChatCell {
let cell = ChatCell()
cell.message = text
// Make the container
let container = UIView()
container.translatesAutoresizingMaskIntoConstraints = false
cell.contentView.addSubview(container)
container.topAnchor.constraintEqualToAnchor(cell.contentView.topAnchor, constant: 8).active = true
container.bottomAnchor.constraintEqualToAnchor(cell.contentView.bottomAnchor, constant: -8).active = true
if leading {
container.leadingAnchor.constraintEqualToAnchor(cell.contentView.leadingAnchor, constant: leading ? 8 : 8*8).active = true
container.trailingAnchor.constraintLessThanOrEqualToAnchor(cell.contentView.trailingAnchor, constant: leading ? -8*8 : -8).active = true
} else {
container.leadingAnchor.constraintGreaterThanOrEqualToAnchor(cell.contentView.leadingAnchor, constant: leading ? 8 : 8*8).active = true
container.trailingAnchor.constraintEqualToAnchor(cell.contentView.trailingAnchor, constant: leading ? -8*8 : -8).active = true
}
// Make the messageLabel.
let messageLabel = UILabel()
messageLabel.numberOfLines = 0
messageLabel.textColor = UIColor.whiteColor()
messageLabel.translatesAutoresizingMaskIntoConstraints = false
container.addSubview(messageLabel)
// Add constraints.
messageLabel.topAnchor.constraintEqualToAnchor(container.topAnchor, constant: 8).active = true
messageLabel.bottomAnchor.constraintEqualToAnchor(container.bottomAnchor, constant: -8).active = true
messageLabel.leadingAnchor.constraintEqualToAnchor(container.leadingAnchor, constant: 8).active = true
messageLabel.trailingAnchor.constraintEqualToAnchor(container.trailingAnchor, constant: -8).active = true
cell.messageLabel = messageLabel
container.backgroundColor = UIColor(red:0.19, green:0.70, blue:1.00, alpha:1.00)
container.layer.cornerRadius = 12.0
return cell
}
}
The cell also includes support for leading and trailing messages, for back and forth conversation. Perhaps make an array of tuples like this:
let messages: [(message: String, leading: Bool)] = [("Hello", true), ("My name is John Doe and this works quite well", false), ("I would agree", true)]
Then in your tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell you could do this:
let cell = ChatCell.messageCell(withText: messages[indexPath.row].message, leading: messages[indexPath.row].leading)
return cell
Let me know if this works for you. I tested it in a Playground and it works as expected
Assuming that your configureChatCell is called from tableView:cellForRowAtIndexPath:, then #Paulw11 is right; cells are reused, so you should only make changes that are unique to that row in the table. In your example, the only calls that you should be making in your method are textView.text = text and the ones to resize the textView to fit. Everything else should go in a dynamic cell prototype in the storyboard or, if you want to do everything in code (which I have a bad feeling you do), then put the rest of the configuration in a UITableViewCell subclass, then register that subclass with your table view.
I write something like this. It's simple but can elucidate solution
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseid", forIndexPath: indexPath)
// Configure the cell...
let contentView = cell.contentView
let subviews = contentView.subviews
for view in subviews {
if 100 == view.tag {
let label = view as! UILabel
label.text = self.datas[indexPath.row]
} else if 200 == view.tag {
view.layer.cornerRadius = 10.0
}
}
return cell
}
the key point is config every thing in tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
the view in code with tag 200 is a background view has same frame with label, I use layout constraint in storyboard to make sure its size and position.

How to set custom margins for a UITableViewCell's .selectedBackgroundView

I'm using a table view to display a tree structure. Each cell corresponds to a node that the user can expand or collapse. The level of each node is visualized by having increasingly large indents at the leading edge of the cells. Those indents are set by using layoutMargins. This seems to work well for the cell's label and separators. Here's some code:
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
let cellLevel = cellLevelForIndexPath(indexPath)
let insets: UIEdgeInsets = UIEdgeInsetsMake(0.0, CGFloat(cellLevel) * 20.0, 0.0, 0.0)
cell.separatorInset = insets
cell.layoutMargins = insets
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cellId") as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cellId")
}
cell!.preservesSuperviewLayoutMargins = false
cell!.backgroundColor = UIColor.clearColor()
let cellLevel = cellLevelForIndexPath(indexPath)
if let textlabel = cell!.textLabel {
textlabel.text = "Cell # level \(cellLevel)"
textlabel.textColor = UIColor.blackColor()
}
cell!.selectedBackgroundView = UIView(frame: CGRectZero)
cell!.selectedBackgroundView.backgroundColor = UIColor.cyanColor()
return cell!
}
The resulting table looks like this:
The question I'm facing now is this: how can I elegantly apply the same indent to the cell's .selectedBackgroundView, so that it appears flush with the text and separator line? The end result should look something like this:
Note: I'm currently achieving the desired effect by making the .selectedBackgroundView more complex and adding background-colored subviews of varying size that effectively mask parts of the cell, e.g. like this:
let maskView = UIView(frame: CGRectMake(0.0, 0.0, CGFloat(cellLevel) * 20.0, cell!.bounds.height))
maskView.backgroundColor = tableView.backgroundColor
cell!.selectedBackgroundView.addSubview(maskView)
But I strongly feel that there must be a nicer way to do this.
Figured out a way to make it work. The trick for me was to stop thinking about the .selectedBackgroundView as the visible highlight itself (and thus trying to mask or resize it) and to treat it more like a canvas instead.
Here's what I ended up doing. First a more convenient way to get the appropriate inset for each level:
let tableLevelBaseInset = UIEdgeInsetsMake(0.0, 20.0, 0.0, 0.0)
private func cellIndentForLevel(cellLevel: Int) -> CGFloat {
return CGFloat(cellLevel) * tableLevelBaseInset.left
}
And then in the cellForRowAtIndexPath:
cell!.selectedBackgroundView = UIView(frame: CGRectZero)
cell!.selectedBackgroundView.backgroundColor = UIColor.clearColor()
let highlight = UIView(frame: CGRectOffset(cell!.bounds, cellIndentForLevel(cellLevel), 0.0))
highlight.backgroundColor = UIColor.cyanColor()
cell!.selectedBackgroundView.addSubview(highlight)
Seems to work nicely.
var selectedView = UIView()
override func awakeFromNib() {
super.awakeFromNib()
self.selectedBackgroundView = {
let view = UIView()
view.backgroundColor = UIColor.clear
selectedView.translatesAutoresizingMaskIntoConstraints = false
selectedView.backgroundColor = .hetro_systemGray6
selectedView.roundAllCorners(radius: 8)
view.addSubview(selectedView)
selectedView.topAnchor.constraint(equalTo: view.topAnchor, constant: 5).isActive = true
selectedView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -5).isActive = true
selectedView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20).isActive = true
selectedView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20).isActive = true
return view
}()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
selectedBackgroundView?.isHidden = false
} else {
selectedBackgroundView?.isHidden = true
}
}

Resources