Why does adding UILabel in subView makes it pixelated - ios

I'm making a message that is shown when the tableView is empty and I've added a label in my subView and it appears to be pixelated. But when I add something in my tableView and delete it, then the message shown (UILabel) is perfectly fine. Can't figure out why.
Adding the label in my self.tableView.backgroundView = emptyLabel solves it but I want to add two labels so I add one in subView that makes it pixelated.
Here is my code:
class ReminderTableViewController: UITableViewController
{
#IBOutlet var myTableView: UITableView!
#IBOutlet weak var dateLabel: UIView!
#IBAction func back(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.separatorColor = UIColor.clear
tableView.separatorStyle = .none
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "details", sender: self)
}
public func buttonImageForEmptyStateView() -> UIImage? {
return UIImage.init(named: "Exclamation Mark Filled-100-2")
}
override func viewDidAppear(_ animated: Bool) {
tableView.reloadData()
self.reloadEmptyState(forTableView: self.tableView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if list.count==0{
let emptyLabel=UILabel(frame: CGRect(x: 0,y: 0, width: self.view.bounds.width, height: self.view.bounds.height))
let emptyLabel2=UILabel(frame: CGRect(x: 0.0,y: 20.0, width: self.view.bounds.width, height: self.view.bounds.height))
self.view.addSubview(emptyLabel2)
self.view.addSubview(emptyLabel)
let emptyImage = UIImageView(image: UIImage(named: "Quote Right Filled-100 (3)"))
emptyImage.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(emptyImage)
emptyImage.alpha=0.1
NSLayoutConstraint.activate([
emptyImage.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
emptyImage.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
emptyImage.heightAnchor.constraint(equalToConstant: 90),
emptyImage.widthAnchor.constraint(equalToConstant: 90)
])
emptyLabel.text = "no present reminders"
emptyLabel.textColor=UIColor.darkGray
emptyLabel.font=UIFont(name: "HelveticaNeue-Light", size: 18)
emptyLabel.textAlignment = NSTextAlignment.center
emptyLabel2.text = "you add by going back to the homescreen"
emptyLabel2.textColor=UIColor.gray
emptyLabel2.font=UIFont(name: "HelveticaNeue-Light", size: 11)
emptyLabel2.textAlignment = NSTextAlignment.center
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.none
return 0
}
else{
return (list.count)
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell=UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
cell.textLabel?.text=list[indexPath.row]
cell.contentView.backgroundColor = UIColor(red:0.89, green:0.89, blue:0.89, alpha:0.7)
cell.textLabel?.textColor=UIColor.black
cell.textLabel?.font=UIFont(name: "HelveticaNeue-Light", size: 16)
return (cell)
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle==UITableViewCellEditingStyle.delete{
list.remove(at: indexPath.row)
tableView.reloadData()
}
}
}

numberOfRowsInSection is call multiple times, so there is not good place to add subview because every time this function is call another UILabel's instance add to view hierarchy.
Remove adding labels in numberOfRowsInSection. Add class variables:
var emptyLabel: UILabel!
var emptyLabel2: UILabel!
var emptyImage: UIImageView!
then add the function
func createEmptyLabels() {
emptyLabel=UILabel(frame: CGRect(x: 0,y: 0, width: self.view.bounds.width, height: self.view.bounds.height))
emptyLabel2=UILabel(frame: CGRect(x: 0.0,y: 20.0, width: self.view.bounds.width, height: self.view.bounds.height))
self.view.addSubview(emptyLabel2)
self.view.addSubview(emptyLabel)
emptyImage = UIImageView(image: UIImage(named: "Quote Right Filled-100 (3)"))
emptyImage.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(emptyImage)
emptyImage.alpha=0.1
NSLayoutConstraint.activate([
emptyImage.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
emptyImage.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
emptyImage.heightAnchor.constraint(equalToConstant: 90),
emptyImage.widthAnchor.constraint(equalToConstant: 90)
])
emptyLabel.text = "no present reminders"
emptyLabel.textColor=UIColor.darkGray
emptyLabel.font=UIFont(name: "HelveticaNeue-Light", size: 18)
emptyLabel.textAlignment = NSTextAlignment.center
emptyLabel2.text = "you add by going back to the homescreen"
emptyLabel2.textColor=UIColor.gray
emptyLabel2.font=UIFont(name: "HelveticaNeue-Light", size: 11)
emptyLabel2.textAlignment = NSTextAlignment.center
emptyLabel.isHidden = true
emptyLabel2.isHidden = true
emptyImage.isHidden = true
}
call this function in viewDidLoad
and in numberOfRowsInSection:
let hideEmptyViews = (list.count != 0)
emptyLabel.isHidden = hideEmptyViews
emptyLabel2.isHidden = hideEmptyViews
emptyImage.isHidden = hideEmptyViews

You are adding the label in numberOfRowsInSection. The problem is that this method is called many times. So you are adding many copies of the label, piled on top of one another, and this makes the label look funny.

Related

Display array of images on a certain amount of tableview cells

I have an UIImageView inside my table view cell, named pic. I want to use an array named colors (filled with UIImages), to display on 3 tableview cells.
I have the ViewController class and the tableview cell class listed below. The tableview displays the imageview pic. I assume you would place the color array in cellForRowAt method.
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var colors:[UIImage] = [
UIImage(named: "blue")!,
UIImage(named: "red")!,
UIImage(named: "red")!
]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 118
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! customtv
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
class customtv: UITableViewCell {
lazy var backView : UIView = {
let view = UIView(frame: CGRect(x: 10, y: 6, width: self.frame.width , height: 110))
view.backgroundColor = .green
return view
}()
lazy var pic : UIImageview = {
let view = UIImageview(frame: CGRect(x: 100, y: 6, width: 100 , height: 100))
view.backgroundColor = .red
return view
}()
override func layoutSubviews() {
backView.clipsToBounds = true
backView.frame = CGRect(x: 0, y: 6, width: bounds.maxX , height: 110)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(animated, animated: true)
addSubview(backView)
addSubview(pic)
}
}
Try with this example below
import UIKit
class ViewController1: UIViewController {
var tableView: UITableView?
var colors:[UIImage] = [
UIImage(named: "blue")!,
UIImage(named: "red")!,
UIImage(named: "red")!
]
override func viewDidLoad() {
super.viewDidLoad()
loadUI()
}
func loadUI() {
tableView = UITableView()
self.view.addSubview(tableView.unsafelyUnwrapped)
tableView?.register(CustomTVC.self, forCellReuseIdentifier: "cell")
tableView?.delegate=self
tableView?.dataSource=self
tableView?.translatesAutoresizingMaskIntoConstraints = false
tableView?.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
tableView?.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor).isActive = true
tableView?.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor).isActive = true
tableView?.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
}
}
extension ViewController1: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 118
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomTVC
cell.pic.image = colors[indexPath.row]
return cell
}
}
class CustomTVC: UITableViewCell {
lazy var backView : UIView = {
let view = UIView()
view.backgroundColor = .green
return view
}()
lazy var pic : UIImageView = {
let view = UIImageView()
view.backgroundColor = .red
return view
}()
override func awakeFromNib() {
super.awakeFromNib()
commonInit()
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override func layoutSubviews() {
backView.clipsToBounds = true
backView.frame = CGRect(x: 0, y: 6, width: bounds.maxX , height: 110)
}
func commonInit() {
contentView.addSubview(backView)
backView.translatesAutoresizingMaskIntoConstraints = false
backView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 4).isActive = true
backView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 4).isActive = true
backView.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -4).isActive = true
backView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -4).isActive = true
backView.addSubview(pic)
pic.translatesAutoresizingMaskIntoConstraints = false
pic.topAnchor.constraint(equalTo: backView.topAnchor, constant: 4).isActive = true
pic.leftAnchor.constraint(equalTo: backView.leftAnchor, constant: 4).isActive = true
pic.bottomAnchor.constraint(equalTo: backView.bottomAnchor, constant: -4).isActive = true
pic.widthAnchor.constraint(equalTo: pic.heightAnchor).isActive = true
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(animated, animated: true)
}
}

Change Spacing of Cocoa Class TableViewCell in ViewController - Swift

I have searched for hours trying stackOverFlows solutions to this issue!!! All of which cause my custom UITable Cells to overlap and not space out. I just want my spacing to be automatic like 'return UITableView.automaticDimension' but say + 8 so that my custom cells aren't right next to each other. I cannot figure it out and maybe it is because I have one line of code that I shouldn't.
This is my cocoa touch class that creates my custom cell 'DiscussionTableViewCell':
class DiscussionTableViewCell: UITableViewCell {
lazy var backView: UIView = {
let view = UIView(frame: CGRect(x: 10, y: 6, width: UIScreen.main.bounds.width - 20, height: 55))
view.backgroundColor = UIColor.rgb(r: 194, g: 208, b: 242)
//view.layer.borderWidth = 3
return view
}()
lazy var discussionTitleLabel: UILabel = {
let LDiscussionTitleLabel = UILabel(frame: CGRect(x: 4, y: 6, width: backView.frame.width - 116, height: 30))
LDiscussionTitleLabel.textAlignment = .left
LDiscussionTitleLabel.font = UIFont.boldSystemFont(ofSize: 18)
return LDiscussionTitleLabel
}()
lazy var discussionDescriptionLabel: UILabel = {
let LDiscussionDescriptionLabel = UILabel(frame: CGRect(x: 4, y: 27, width: backView.frame.width - 30, height: 30))
LDiscussionDescriptionLabel.textAlignment = .left
LDiscussionDescriptionLabel.font = UIFont.systemFont(ofSize: 16)
LDiscussionDescriptionLabel.textColor = UIColor.gray
return LDiscussionDescriptionLabel
}()
override func awakeFromNib() {
super.awakeFromNib()
//layoutMargins = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
// Initialization code
}
override func layoutSubviews() {
//super.layoutSubviews()
contentView.backgroundColor = UIColor.rgb(r: 203, g: 215, b: 242)
backgroundColor = UIColor.yellow
backView.layer.cornerRadius = 5
backView.clipsToBounds = true
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
addSubview(backView)
backView.addSubview(discussionTitleLabel)
backView.addSubview(discussionDescriptionLabel)
// Configure the view for the selected state
}
}
And a section of my ViewController that applies to assigning text to the table cell, and spacing between cells:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return discussionTitles.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! DiscussionTableViewCell
cell.discussionTitleLabel.text = discussionTitles[indexPath.row]
cell.discussionDescriptionLabel.text = discussionDescriptions[indexPath.row]
return cell
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if (singlePageVar == 100) {
return 1407//UITableView.automaticDimension
}
return 62//UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("section: \(indexPath.section)")
print("row: \(indexPath.row)")
var topicNumberRow = (indexPath.row)
mainTopicNumberRow = topicNumberRow
DiscussionBoardTopicThread()
}
//function I call in viewdidload to show table
func setupDiscussionBoard() {
discussionBoardView.separatorStyle = .none
view.addSubview(discussionBoardView)
discussionBoardView.backgroundColor = UIColor(red: 203/255, green: 215/255, blue: 242/255, alpha: 1.0)
discussionBoardView.dataSource = self
discussionBoardView.delegate = self
discussionBoardView.translatesAutoresizingMaskIntoConstraints = false
discussionBoardView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
discussionBoardView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
discussionBoardView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
discussionBoardView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
discussionBoardView.register(DiscussionTableViewCell.self, forCellReuseIdentifier: "cell")
}
}

How to fix dynamic height for individual cells as UIautodimensions is not working

I am creating a wall page like twitter or Facebook in which user can post on the wall it can include image and just text. So based on the content the cell's heights must change, if the post is of one line the row height must be appropriate.
I tried using UITableViewAutomaticDimensions, but its not working with my code please do help me.
import UIKit
class wallPageViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var tableOfApps : UITableView?
var appNames: [String]? = []
var apps: [wallPageModel]?
var dynamic_height : CGFloat = 150.0
var addPost : UITextField?
var readMore : UITextView?
func loadTableOfApps(){
//appNames = ["jkbajdba", "abfajfb", "akjbfkjag", "ahbfkajf" ]
let provider = wallPageProvider()
apps = provider.getApps()
let tableHeight = view.frame.size.height
tableOfApps = UITableView(frame: CGRect(x: 10, y: 60, width: 300, height: tableHeight))
tableOfApps!.delegate = self
tableOfApps!.dataSource = self
tableOfApps?.separatorStyle = UITableViewCellSeparatorStyle.none
//self.tableOfApps?.rowHeight = UITableViewAutomaticDimension
//self.tableOfApps?.estimatedRowHeight = UITableViewAutomaticDimension
print("load table of apps")
view.addSubview(tableOfApps!)
}
override func viewDidLoad() {
super.viewDidLoad()
loadTableOfApps()
loadAddPost()
tableOfApps?.estimatedRowHeight = 150.0
tableOfApps?.rowHeight = UITableViewAutomaticDimension
view.backgroundColor = UIColor(red: 232/255, green: 234/255, blue: 246/255, alpha: 1.0)
// Do any additional setup after loading the view.
}
func loadAddPost(){
addPost = UITextField(frame: CGRect(x: 10, y: 20, width: 300, height: 30))
addPost?.placeholder = "Stay safe, post a tip!"
addPost?.isUserInteractionEnabled = true
addPost?.borderStyle = UITextBorderStyle.roundedRect
addPost?.autocapitalizationType = .none
view.addSubview(addPost!)
addPost?.addTarget(self, action: #selector(writeComment), for: UIControlEvents.touchDown)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("app coun\(apps!.count)")
return apps!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell : wallModelTableViewCell?
cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? wallModelTableViewCell
if cell == nil {
cell = wallModelTableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
}
let app = apps![indexPath.row]//reading the array of data hence provider
//association of provider and view
//this is the processs from where view can read the data from provide
cell!.iconImageLabel!.image = app.icon
cell!.titleLabel!.text = app.title
cell?.backgroundColor = UIColor.white
cell!.commentsLabel?.image = app.comments_Label
cell?.commentsLabel?.center = CGPoint(x: tableView.frame.size.width/2, y: dynamic_height-20)
cell?.likeButtonLabel?.image = app.likeButton
cell?.likeButtonLabel?.center = CGPoint(x: (tableView.frame.size.width/2)-130, y: dynamic_height-20)
/*cell?.likeButtonLabel?.leftAnchor.constraint(equalTo: tableView.leftAnchor, constant: 50)*/
cell!.feedTextLabel!.text = app.feedText
cell?.feedTextLabel?.sizeToFit()//so that it can expand the data more than two lines
cell?.feedTextLabel?.backgroundColor = UIColor.clear
//Limiting UIlabel to 125 characters
if (cell?.feedTextLabel?.text.count)! > 125{
/*
let index = cell?.feedTextLabel?.text.index((cell?.feedTextLabel?.text.startIndex)!, offsetBy: 125)
cell?.feedTextLabel?.text = cell?.feedTextLabel?.text.substring(to: index!)
cell?.feedTextLabel?.text = cell?.feedTextLabel?.text.appending("...")*/
//cell?.feedTextLabel?.attributedText = NSAttributedString(string: "...readmore")
}
cell?.layer.cornerRadius = 6.0
cell?.isUserInteractionEnabled = false
cell?.titleLabel?.isUserInteractionEnabled = true
tableOfApps?.backgroundColor = UIColor.clear
tableOfApps?.backgroundView?.isOpaque = false
tableOfApps!.estimatedRowHeight = 150.0
tableOfApps!.rowHeight = UITableViewAutomaticDimension
print("table view cell for row")
/*let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector( self.labelAction(gesture:)))
cell?.feedTextLabel?.addGestureRecognizer(tap)
cell?.feedTextLabel?.isUserInteractionEnabled = true
tap.delegate = self as! UIGestureRecognizerDelegate*/
return cell!
}
/*#objc func labelAction(gesture: UITapGestureRecognizer){
}*/
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
print("height for row")
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 150.0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
#objc func writeComment(){
let addComment = addCommentViewController()
navigationController?.pushViewController(addComment, animated: true)
}
/*
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
I want each row must have dynamic height as the content is provided by the user if the content contains 150 characters the height of the cell must be 200+ if content contains less than 125 characters the height must be as adequate to read.

UITableview scrolling is not responding properly?

booktable.frame = CGRect(x: 0, y: booktopview.bounds.height, width: screenWidth, height: screenHeight-booktopview.bounds.height-tabbarView.bounds.height)
booktable.register(UITableViewCell.self, forCellReuseIdentifier: "mycell")
booktable.dataSource = self
booktable.delegate = self
booktable.separatorColor = UIColor.lightGray
booktable.backgroundColor = UIColor.clear
booktable.separatorStyle = .singleLine
bookview.addSubview(booktable)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if(tableView == booktable)
{
let cell1 = booktable.dequeueReusableCell(withIdentifier: "mycell")
for object in (cell1?.contentView.subviews)!
{
object.removeFromSuperview();
}
let img :UIImageView = UIImageView()
let lbl : UILabel = UILabel()
img.frame = CGRect(x: 15, y: 15, width: 80, height: 130)
img.image = imgarray[indexPath.row]
img.layer.borderWidth = 1.0
img.layer.borderColor = UIColor.lightGray.cgColor
cell1?.contentView.addSubview(img)
imgheight = img.bounds.height
lbl.frame = CGRect(x: img.bounds.width + 40, y: (imgheight+40-80)/2, width: booktable.bounds.width-img.bounds.width + 40 - 100, height: 80)
lbl.text = imgname[indexPath.row]
lbl.numberOfLines = 0
lbl.textAlignment = .left
lbl.font = UIFont(name: "Arial", size: 23)
lbl.textColor = UIColor.black
cell1?.selectionStyle = .none
cell1?.contentView.addSubview(lbl)
return cell1!
}
The code shown above is for book table, which sometimes scrolls like normal and sometimes not scrolling at all. I am doing all the code programatically. I have tested this on both simulators and devices but still the problem exists. Any help is appreciated...
Create Custom UITableViewCell, let's say it is ListTableCell
class ListTableCell: UITableViewCell {
#IBOutlet weak var lblTemp: UILabel!
#IBOutlet weak var imgTemp: UIImage!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
I've created UITableViewCell with xib like this and bind IBOutlets
Let's say we have struct Model and array like this
struct Model {
let image : UIImage
let name: String
}
for i in 0...10 {
let model = Model(image: #imageLiteral(resourceName: "Cat03"), name: "Temp \(i)")
array.append(model)
}
Now on ViewController viewDidLoad() method,
tableView.register(UINib(nibName: "ListTableCell", bundle: nil), forCellReuseIdentifier: "ListTableCell")
Implement UITableViewDataSource methods like this,
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ListTableCell") as! ListTableCell
let model = array[indexPath.row]
cell.lblTemp.text = model.name
cell.imgTemp.image = model.image
return cell
}
FYI
For different tableviews, you can create different custom cell the same way and cellForRowAt indexPath and numberOfRowsInSection method will change appropriately.
Let me know in case of any queries.
UPDATE
Follow this and this to create CustomTableCell programmatically

How To Share Same UIView Between Multiple UITableView Cells

Objective
When the user clicks on any of the 3 blue buttons, all buttons change to the same color.
Note: this is an abstraction of a shared progress view problem, it's therefore important that only one UIView is shared (or mimicked) across my three rows
Here is a compilable Swift project:
import UIKit
class ToggleButton: UIButton {
var connectedView: UIView?
func onPress() {
self.isHidden = true
self.connectedView?.isHidden = false
}
}
class ViewController : UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView: UITableView = UITableView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
var myView: UIView? = nil
var toggleBtn: ToggleButton? = nil
override func viewDidLoad() {
self.setupTableView()
}
fileprivate func setupTableView() {
self.tableView.dataSource = self
self.tableView.delegate = self
self.tableView.backgroundColor = UIColor.white
self.tableView.isOpaque = true
self.view.addSubview(self.tableView)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "CellIdentifier")
let frame = CGRect(x: 10, y: 10, width: 30, height: 30)
if let view = self.myView, let btn = self.toggleBtn {
cell.addSubview(view)
cell.addSubview(btn)
} else {
let myView = UIView(frame: frame)
myView.backgroundColor = UIColor.green
myView.isHidden = true
cell.addSubview(myView)
let toggleBtn = ToggleButton(frame: frame)
toggleBtn.backgroundColor = UIColor.blue
toggleBtn.addTarget(self, action: #selector(onPress), for: .touchUpInside)
toggleBtn.connectedView = myView
cell.addSubview(toggleBtn)
}
return cell
}
#objc func onPress(_ sender: Any) {
if let button = sender as? ToggleButton {
button.onPress()
}
}
}
Any help appreciated.
The concept of UITableViewCell is made to be very independent each other.
So the only thing you can do it having a bool flag in your ViewController, then you init your 3 cells with this flags.
And finally each time the button is pressed you toggle the flag en reload your tableView.

Resources