How To Share Same UIView Between Multiple UITableView Cells - ios

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.

Related

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

Add Subview To Custom UI Button Class

Objective:
When the user clicks the custom button, a blank UIView should appear covering the button.
I've added my code to a new Swift project which looks like this
import UIKit
class DownloadUIButton: UIButton {
var isDownloading: Bool? = false
func addView() {
let view = UIView(frame: self.frame)
view.backgroundColor = UIColor.white
self.addSubview(view)
}
}
class ViewController : UIViewController, UITableViewDelegate, UITableViewDataSource {
fileprivate let tableView: UITableView = UITableView(frame: CGRect.init(x: 0, y: 0, width: 300, height: 300), style: UITableViewStyle.plain)
override func viewDidLoad() {
self.setupTableView()
}
fileprivate func setupTableView() {
self.tableView.dataSource = self
self.tableView.delegate = self
tableView.backgroundColor = UIColor.white
tableView.isOpaque = true
view.addSubview(self.tableView)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "CellIdentifier")
let buttonSize = 30
let btn = DownloadUIButton(frame: CGRect(x: 10, y: 10, width: buttonSize, height: buttonSize))
btn.backgroundColor = UIColor.red
btn.addTarget(self, action:#selector(handleDownload(_:)), for: .touchUpInside)
cell.addSubview(btn)
return cell
}
#objc func handleDownload(_ btn: DownloadUIButton) {
btn.addView()
}
}
However, the project gives this error:
2017-10-28 12:55:41.558522+0100 TestProject[21392:1779236] *** Terminating app due to uncaught exception 'CALayerInvalid', reason: 'layer is a part of cycle in its layer tree'
To make a view appear in front of your button, I'd just make them sibling views with the same frame. Have the custom view's isHidden set to true at launch time, and when the button's clicked, set the button's isHidden to true and the custom view's isHidden to false. Alternately, if you actually want the button to be visible behind transparent parts of the custom view, you can use sendSubview(toBack:) to make the button appear behind the custom view.

Blank Menu Button with Swift Slide Menu

I have a weird issue when creating the Slide out menu in swift,
I'm building the menu using AKSwiftSlideMenu as a reference,
This only happens on the ViewControllers that have a UITableViewDataSource, UITableViewDelegate.
If I go to the other view controllers without one, the menu shows up fine.
Below is my code for BaseViewController
class BaseViewController: UIViewController, SlideMenuDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func slideMenuItemSelectedAtIndex(_ index: Int32) {
let topViewController : UIViewController = self.navigationController!.topViewController!
print("View Controller is : \(topViewController) \n", terminator: "")
switch(index){
case 0:
print("Locations\n", terminator: "")
self.openViewControllerBasedOnIdentifier("Locations")
break
case 1:
print("Offers\n", terminator: "")
self.openViewControllerBasedOnIdentifier("Offers")
break
case 2:
print("Feedback\n", terminator: "")
self.openViewControllerBasedOnIdentifier("Feedback")
break
case 3:
print("About\n", terminator: "")
self.openViewControllerBasedOnIdentifier("About")
break
case 4:
for key in UserDefaults.standard.dictionaryRepresentation().keys {
UserDefaults.standard.removeObject(forKey: key)
}
//fb logout
if(FBSDKAccessToken.current() != nil) {
FBSDKAccessToken.setCurrent(nil)
FBSDKProfile.setCurrent(nil)
}
self.openViewControllerBasedOnIdentifier("SocialLogin")
default:
print("default\n", terminator: "")
}
}
func openViewControllerBasedOnIdentifier(_ strIdentifier:String){
let destViewController : UIViewController = self.storyboard!.instantiateViewController(withIdentifier: strIdentifier)
let topViewController : UIViewController = self.navigationController!.topViewController!
if (topViewController.restorationIdentifier! == destViewController.restorationIdentifier!){
print("Same VC")
} else {
self.navigationController!.pushViewController(destViewController, animated: true)
}
}
func addSlideMenuButton(){
let btnShowMenu = UIButton(type: UIButtonType.system)
btnShowMenu.setImage(self.defaultMenuImage(), for: UIControlState())
btnShowMenu.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
btnShowMenu.addTarget(self, action: #selector(BaseViewController.onSlideMenuButtonPressed(_:)), for: UIControlEvents.touchUpInside)
let customBarItem = UIBarButtonItem(customView: btnShowMenu)
self.navigationItem.leftBarButtonItem = customBarItem;
}
func defaultMenuImage() -> UIImage {
var defaultMenuImage = UIImage()
UIGraphicsBeginImageContextWithOptions(CGSize(width: 30, height: 22), false, 0.0)
UIColor.black.setFill()
UIBezierPath(rect: CGRect(x: 0, y: 3, width: 30, height: 1)).fill()
UIBezierPath(rect: CGRect(x: 0, y: 10, width: 30, height: 1)).fill()
UIBezierPath(rect: CGRect(x: 0, y: 17, width: 30, height: 1)).fill()
UIColor.white.setFill()
UIBezierPath(rect: CGRect(x: 0, y: 4, width: 30, height: 1)).fill()
UIBezierPath(rect: CGRect(x: 0, y: 11, width: 30, height: 1)).fill()
UIBezierPath(rect: CGRect(x: 0, y: 18, width: 30, height: 1)).fill()
defaultMenuImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return defaultMenuImage;
}
func onSlideMenuButtonPressed(_ sender : UIButton){
if (sender.tag == 10)
{
// To Hide Menu If it already there
self.slideMenuItemSelectedAtIndex(-1);
sender.tag = 0;
let viewMenuBack : UIView = view.subviews.last!
UIView.animate(withDuration: 0.3, animations: { () -> Void in
var frameMenu : CGRect = viewMenuBack.frame
frameMenu.origin.x = -1 * UIScreen.main.bounds.size.width
viewMenuBack.frame = frameMenu
viewMenuBack.layoutIfNeeded()
viewMenuBack.backgroundColor = UIColor.clear
}, completion: { (finished) -> Void in
viewMenuBack.removeFromSuperview()
})
return
}
sender.isEnabled = false
sender.tag = 10
let menuVC : MenuViewController = self.storyboard!.instantiateViewController(withIdentifier: "MenuViewController") as! MenuViewController
menuVC.btnMenu = sender
menuVC.delegate = self
self.view.addSubview(menuVC.view)
self.addChildViewController(menuVC)
menuVC.view.layoutIfNeeded()
menuVC.view.frame=CGRect(x: 0 - UIScreen.main.bounds.size.width, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height);
UIView.animate(withDuration: 0.3, animations: { () -> Void in
menuVC.view.frame=CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height);
sender.isEnabled = true
}, completion:nil)
}
}
MenuViewController
protocol SlideMenuDelegate {
func slideMenuItemSelectedAtIndex(_ index : Int32)
}
class MenuViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
/**
* Array to display menu options
*/
#IBOutlet var tblMenuOptions : UITableView!
/**
* Transparent button to hide menu
*/
#IBOutlet var btnCloseMenuOverlay : UIButton!
/**
* Array containing menu options
*/
var arrayMenuOptions = [Dictionary<String,String>]()
/**
* Menu button which was tapped to display the menu
*/
var btnMenu : UIButton!
/**
* Delegate of the MenuVC
*/
var delegate : SlideMenuDelegate?
override func viewDidLoad() {
super.viewDidLoad()
tblMenuOptions.tableFooterView = UIView()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateArrayMenuOptions()
}
func updateArrayMenuOptions(){
arrayMenuOptions.append(["title":"Locations", "icon":"LocationIcon"])
arrayMenuOptions.append(["title":"Offers", "icon":"OffersIcon"])
arrayMenuOptions.append(["title":"Feedback", "icon":"FeedbackIcon"])
arrayMenuOptions.append(["title":"About", "icon":"AboutIcon"])
arrayMenuOptions.append(["title":"Logout", "icon":"LogoutIcon"])
tblMenuOptions.reloadData()
}
#IBAction func onCloseMenuClick(_ button:UIButton!){
btnMenu.tag = 0
if (self.delegate != nil) {
var index = Int32(button.tag)
if(button == self.btnCloseMenuOverlay){
index = -1
}
delegate?.slideMenuItemSelectedAtIndex(index)
}
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.view.frame = CGRect(x: -UIScreen.main.bounds.size.width, y: 0, width: UIScreen.main.bounds.size.width,height: UIScreen.main.bounds.size.height)
self.view.layoutIfNeeded()
self.view.backgroundColor = UIColor.clear
}, completion: { (finished) -> Void in
self.view.removeFromSuperview()
self.removeFromParentViewController()
})
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cellMenu")!
cell.selectionStyle = UITableViewCellSelectionStyle.none
cell.layoutMargins = UIEdgeInsets.zero
cell.preservesSuperviewLayoutMargins = false
cell.backgroundColor = UIColor.clear
let lblTitle : UILabel = cell.contentView.viewWithTag(101) as! UILabel
let imgIcon : UIImageView = cell.contentView.viewWithTag(100) as! UIImageView
imgIcon.image = UIImage(named: arrayMenuOptions[indexPath.row]["icon"]!)
lblTitle.text = arrayMenuOptions[indexPath.row]["title"]!
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let btn = UIButton(type: UIButtonType.custom)
btn.tag = indexPath.row
self.onCloseMenuClick(btn)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayMenuOptions.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1;
}
}
a example of view controller where this happens
class LocationViewController: BaseViewController, CLLocationManagerDelegate, UITableViewDataSource, UITableViewDelegate {
var locItems:Array<LocItems>?
var locItemsWrapper:LocItemsWrapper?
var isLoadingLocItems = false
private var tb: UITableView?
override func viewDidLoad() {
super.viewDidLoad()
//set up tableview
tb = UITableView()
//Set button to open up menu
self.addSlideMenuButton()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (self.locItems == nil) {
return 0
}
return self.locItems!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "locCell", for: indexPath) as! LocItemCell
if(self.locItems != nil && self.locItems!.count >= indexPath.row) {
let locItem = self.locItems![indexPath.row]
let rowsLoaded = self.locItems!.count
if (!self.isLoadingLocItems && (indexPath.row >= (rowsLoaded - rowsToLoadFromBottom))) {
let totalRows = self.locItemsWrapper!.count!
let remainingLocItemsToLoad = totalRows - rowsLoaded
if(remainingLocItemsToLoad > 0) {
self.loadMoreLocItems()
}
}
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if(self.locItems!.count >= indexPath.row) {
selectedLocId = self.locItems![indexPath.row].id!
selectedLocBg = self.locItems![indexPath.row].locationBackground!
//TODO: Set up Switch on api call
let parameters = [
"locId": selectedLocId
]
}
}
override func prepare(for segue: (UIStoryboardSegue!), sender: Any!) {
if(segue.identifier == "showCongratOffer") {
let svc = segue.destination as! CongratOfferViewController
svc.offerId = selectedLocId
svc.type = 1
}
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if((indexPath.row % 2) == 0) {
cell.backgroundColor = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1.0)
} else {
cell.backgroundColor = UIColor.white
}
}
I know it's a lot of code, I tried to cut out pieces in the example where it happens as much as possible while leaving the menu code complete,
I would really appreciate if someone could help me with this issue or point me in the right direction.
A picture of the tableview before I open the menu,
A picture of the storyboard,
The top left controller can be ignored,
from login (top middle), we go to locations (bottom right, bottom middle) where the menu exists,
about (top right) will show the menu properly without the blank space,
the menu controller is bottom left.
The menu still works, though the empty space shows up in controllers with a UITableViewDataSource, UITableViewDelegate.
UPDATE: Looking at the view and how it gets built, I've found the menu height constraint is different. It's not getting set after menuVC.view.layoutIfNeeded() in BaseViewController.
print(self.childViewControllers[0].topLayoutGuide)
Empty Space Issue -> <_UILayoutGuide: 0x7fce6e7115e0; frame = (0 0; 0 0); hidden = YES; layer = <CALayer: 0x600000238700>>
Working -> <_UILayoutGuide: 0x7fce6e51ad30; frame = (0 0; 0 64); hidden = YES; layer = <CALayer: 0x60000023c9a0>>
How would you change just the height constraint on the view?
I can get the read-only view constraints like so,
self.childViewControllers[0].view.constraints
I see the issue now. What you need to do is copy the cell from your TableView, delete the original cell, make sure the TableView is completely empty, and paste the Cell back in. You can do this manually as well by making a new cell entirely. BTW, the issue is that there is an empty space above your cell which you need to remove from your TableView.

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