Change Spacing of Cocoa Class TableViewCell in ViewController - Swift - ios

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")
}
}

Related

black area above navigation bar appears when search bar is not active?

I have a search controller added to navigationController.searchController. When the screen initially loads there is a black space above the navigation bar. Only when I tap on the search bar this space correctly shows white. When I tap off the search bar, this area shows black again.
import UIKit
import Foundation
import InstantSearch
class AlgoliaViewController: UIViewController, UISearchBarDelegate {
let userHitsInteractor: HitsInteractor<User> = .init(infiniteScrolling: .off, showItemsOnEmptyQuery: false)
let businessHitsInteractor: HitsInteractor<Business> = .init(infiniteScrolling: .off, showItemsOnEmptyQuery: false)
let multiSearch = MultiIndexSearcher(appID: APP_ID, apiKey: APP_KEY, indexNames: ["dev_USERS","dev_BUSINESS"])
lazy var multiConnector: MultiIndexSearchConnector = .init(searcher: multiSearch, indexModules: [
.init(indexName: "dev_USERS",
hitsInteractor: userHitsInteractor),
.init(indexName: "dev_BUSINESS",
hitsInteractor: businessHitsInteractor)
], searchController: searchController, hitsController: hitsTableViewController)
lazy var searchController: UISearchController = .init(searchResultsController: hitsTableViewController)
let hitsTableViewController = MultiIndexController()
let statsInteractor: StatsInteractor = .init()
override func viewDidLoad() {
super.viewDidLoad()
multiConnector.connect()
multiSearch.search()
statsInteractor.connectController(self)
setupUI()
}
func setupUI() {
view.backgroundColor = .white
navigationItem.searchController = searchController
navigationController?.navigationBar.backgroundColor = .white
// navigationItem.titleView = searchController.searchBar
navigationController?.navigationBar.backgroundColor = .white
navigationController?.navigationBar.isTranslucent = false
navigationController?.hidesBarsOnSwipe = false
searchController.hidesNavigationBarDuringPresentation = false
searchController.showsSearchResultsController = true
searchController.automaticallyShowsCancelButton = false
searchController.searchBar.delegate = self
searchController.obscuresBackgroundDuringPresentation = false
hitsTableViewController.view.backgroundColor = .white
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchController.isActive = true
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
searchController.isActive = false
}
}
extension AlgoliaViewController: StatsTextController {
func setItem(_ item: String?) {
title = item
}
}
class MultiIndexController: UITableViewController, MultiIndexHitsController {
var hitsSource: MultiIndexHitsSource?
let cellID = "cellID"
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(ResultsItemCell.self, forCellReuseIdentifier: cellID)
setupUI()
self.tableView.keyboardDismissMode = .onDrag
}
func setupUI() {
view.backgroundColor = .white
tableView.backgroundColor = .white
tableView.separatorStyle = .none
}
override func numberOfSections(in tableView: UITableView) -> Int {
return (hitsSource?.numberOfSections())!
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (hitsSource?.numberOfHits(inSection: section)) ?? 0
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 50))
let sectionTitle = UILabel(frame: CGRect(x: 0, y: 0, width: headerView.frame.width, height: headerView.frame.height))
Utilities.styleLblFont(sectionTitle, fontName: "Cabin-SemiBold", fontSize: 18, color: .black)
var headertitle = ""
switch section {
case 0:
print("section 0")
headertitle = "People"
case 1:
print("section 1")
headertitle = "Businesses"
default:
break
}
headerView.backgroundColor = .white
sectionTitle.text = headertitle
headerView.addSubview(sectionTitle)
return headerView
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellID) as! ResultsItemCell
switch indexPath.section {
case 0:
if let item: User = try? hitsSource?.hit(atIndex: indexPath.row, inSection: indexPath.section) {
cell.nameLbl.text = item.userName
cell.avatar.loadImage(item.profilePhotoUrl)
cell.jobTitleLbl.text = item.userType
}
case 1:
if let business: Business = try? hitsSource?.hit(atIndex: indexPath.row, inSection: indexPath.section) {
cell.nameLbl.text = business.businessName
cell.avatar.loadImage(business.businessAvatarUrl)
cell.jobTitleLbl.text = business.mission
}
default:
break
}
return cell
}
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 50))
let seeResultsBtn = UIButton(frame: CGRect(x: 0, y: 0, width: footerView.frame.width, height: footerView.frame.height))
var footerTitle = ""
switch section {
case 0:
footerTitle = "See all people"
case 1:
footerTitle = "See all businesses"
default:
footerTitle = "See all results"
}
footerView.addSubview(seeResultsBtn)
seeResultsBtn.translatesAutoresizingMaskIntoConstraints = false
seeResultsBtn.centerYAnchor.constraint(equalTo: footerView.centerYAnchor).isActive = true
seeResultsBtn.centerXAnchor.constraint(equalTo: footerView.centerXAnchor).isActive = true
Utilities.buttonTitle(seeResultsBtn, title: footerTitle, titleColour: .jabiMain, fontName: "Cabin-Medium", fontSize: 16)
footerView.backgroundColor = .white
return footerView
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 50
}
}
Please see the screenshots:

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)
}
}

After update tableview did not work. Why is this happen?

I have interesting problem in my machine. I want to make table view and I did it many times but after the update its not working. Is the making way is changed or what? Can anyone help me?
Here my controller and delegate methods:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let tableView: UITableView = {
let tv = UITableView()
tv.separatorStyle = .none
tv.allowsSelection = false
return tv
}()
override func viewDidLoad() {
super.viewDidLoad()
titleOfapp ()
setupTableView()
}
let sipCellId = "sipCellId"
func titleOfapp () {
let titleLabelMarka = UILabel()
titleLabelMarka.textAlignment = .center
titleLabelMarka.text = "Pak Terminal"
titleLabelMarka.textColor = UIColor.white
titleLabelMarka.font = UIFont(name:"Comfortaa-bold", size: 24)
navigationItem.titleView = titleLabelMarka
navigationController?.navigationBar.barTintColor = UIColor.init(red: 80.0/255.0, green: 197.0/255.0, blue: 247.0/255.0, alpha: 1.0)
}
func setupTableView() {
tableView.delegate = self
tableView.dataSource = self
tableView.register(sipCell.self, forCellReuseIdentifier: sipCellId)
view.addSubview(tableView)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: sipCellId, for: indexPath) as! sipCell
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
}
And here my custom cell code:
class sipCell: UITableViewCell {
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let cellView: UIView = {
let view = UIView()
view.backgroundColor = .red
return view
}()
var detailLabel: UILabel = {
let tf = UILabel()
tf.text = "mehmet akyol"
tf.textColor = .black
tf.font = UIFont(name: "Comfortaa-Bold", size: 13)
return tf
}()
func setup(){
addSubview(cellView)
addSubview(detailLabel)
cellView.anchor(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, paddingTop: 4, paddingLeft: 8, paddingBottom: 4, paddingRight: 8, width: 60, height: 55)
detailLabel.anchor(top: nil, left: cellView.leftAnchor, bottom: nil, right: rightAnchor, paddingTop: 4, paddingLeft: 8, paddingBottom: 4, paddingRight: 8, width: 60, height: 40)
detailLabel.centerYAnchor.constraint(equalTo: cellView.centerYAnchor).isActive = true
}
}
You need to create constraints for the table
view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor),
tableView.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor),
tableView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor)
])
or set a frame

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

Why does adding UILabel in subView makes it pixelated

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.

Resources