If no Table View results, display "No Results" on screen - ios

I have a tableview, where sometimes there might not be any results to list, so I would like to put something up that says "no results" if there are no results (either a label or one table view cell?).
Is there an easiest way to do this?
I would try a label behind the tableview then hide one of the two based on the results, but since I'm working with a TableViewController and not a normal ViewController I'm not sure how smart or doable that is.
I'm also using Parse and subclassing as a PFQueryTableViewController:
#interface TableViewController : PFQueryTableViewController
I can provide any additional details needed, just let me know!
TableViewController Scene in Storyboard:
EDIT: Per Midhun MP, here's the code I'm using
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSInteger numOfSections = 0;
if ([self.stringArray count] > 0)
{
self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
numOfSections = 1;
//yourTableView.backgroundView = nil;
self.tableView.backgroundView = nil;
}
else
{
UILabel *noDataLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.tableView.bounds.size.width, self.tableView.bounds.size.height)];
noDataLabel.text = #"No data available";
noDataLabel.textColor = [UIColor blackColor];
noDataLabel.textAlignment = NSTextAlignmentCenter;
//yourTableView.backgroundView = noDataLabel;
//yourTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
self.tableView.backgroundView = noDataLabel;
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
return numOfSections;
}
And here's the View I'm getting, it still has separator lines. I get the feeling that this is some small change, but I'm not sure why separator lines are showing up?

You can easily achieve that by using backgroundView property of UITableView.
Objective C:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSInteger numOfSections = 0;
if (youHaveData)
{
yourTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
numOfSections = 1;
yourTableView.backgroundView = nil;
}
else
{
UILabel *noDataLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, yourTableView.bounds.size.width, yourTableView.bounds.size.height)];
noDataLabel.text = #"No data available";
noDataLabel.textColor = [UIColor blackColor];
noDataLabel.textAlignment = NSTextAlignmentCenter;
yourTableView.backgroundView = noDataLabel;
yourTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
return numOfSections;
}
Swift:
func numberOfSections(in tableView: UITableView) -> Int
{
var numOfSections: Int = 0
if youHaveData
{
tableView.separatorStyle = .singleLine
numOfSections = 1
tableView.backgroundView = nil
}
else
{
let noDataLabel: UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: tableView.bounds.size.height))
noDataLabel.text = "No data available"
noDataLabel.textColor = UIColor.black
noDataLabel.textAlignment = .center
tableView.backgroundView = noDataLabel
tableView.separatorStyle = .none
}
return numOfSections
}
Reference UITableView Class Reference
backgroundView Property
The background view of the table view.
Declaration
Swift
var backgroundView: UIView?
Objective-C
#property(nonatomic, readwrite, retain) UIView *backgroundView
Discussion
A table view’s background view is automatically resized to match the
size of the table view. This view is placed as a subview of the table
view behind all cells, header views, and footer views.
You must set this property to nil to set the background color of the
table view.

For Xcode 8.3.2 - Swift 3.1
Here is a not-so-well-known but incredibly easy way to achieve adding a "No Items" view to an empty table view that goes back to Xcode 7. I'll leave it to you control that logic that adds/removes the view to the table's background view, but here is the flow for and Xcode (8.3.2) storyboard:
Select the scene in the Storyboard that has your table view.
Drag an empty UIView to the "Scene Dock" of that scene
Add a UILabel and any constraints to the new view and then create an IBOutlet for that view
Assign that view to the tableView.backgroundView
Behold the magic!
Ultimately this works anytime you want to add a simple view to your view controller that you don't necessarily want to be displayed immediately, but that you also don't want to hand code.

Swift Version of above code :-
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
var numOfSection: NSInteger = 0
if CCompanyLogoImage.count > 0 {
self.tableView.backgroundView = nil
numOfSection = 1
} else {
var noDataLabel: UILabel = UILabel(frame: CGRectMake(0, 0, self.tableView.bounds.size.width, self.tableView.bounds.size.height))
noDataLabel.text = "No Data Available"
noDataLabel.textColor = UIColor(red: 22.0/255.0, green: 106.0/255.0, blue: 176.0/255.0, alpha: 1.0)
noDataLabel.textAlignment = NSTextAlignment.Center
self.tableView.backgroundView = noDataLabel
}
return numOfSection
}
But If you are loading Information From a JSON , you need to check whether the JSON is empty or not , therefor if you put code like this it initially shows "No data" Message then disappear. Because after the table reload data the message hide. So You can put this code where load JSON data to an array. SO :-
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func extract_json(data:NSData) {
var error: NSError?
let jsonData: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers , error: &error)
if (error == nil) {
if let jobs_list = jsonData as? NSArray
{
if jobs_list.count == 0 {
var noDataLabel: UILabel = UILabel(frame: CGRectMake(0, 0, self.tableView.bounds.size.width, self.tableView.bounds.size.height))
noDataLabel.text = "No Jobs Available"
noDataLabel.textColor = UIColor(red: 22.0/255.0, green: 106.0/255.0, blue: 176.0/255.0, alpha: 1.0)
noDataLabel.textAlignment = NSTextAlignment.Center
self.tableView.backgroundView = noDataLabel
}
for (var i = 0; i < jobs_list.count ; i++ )
{
if let jobs_obj = jobs_list[i] as? NSDictionary
{
if let vacancy_title = jobs_obj["VacancyTitle"] as? String
{
CJobTitle.append(vacancy_title)
if let vacancy_job_type = jobs_obj["VacancyJobType"] as? String
{
CJobType.append(vacancy_job_type)
if let company_name = jobs_obj["EmployerCompanyName"] as? String
{
CCompany.append(company_name)
if let company_logo_url = jobs_obj["EmployerCompanyLogo"] as? String
{
//CCompanyLogo.append("http://google.com" + company_logo_url)
let url = NSURL(string: "http://google.com" + company_logo_url )
let data = NSData(contentsOfURL:url!)
if data != nil {
CCompanyLogoImage.append(UIImage(data: data!)!)
}
if let vacancy_id = jobs_obj["VacancyID"] as? String
{
CVacancyId.append(vacancy_id)
}
}
}
}
}
}
}
}
}
do_table_refresh();
}
func do_table_refresh() {
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
return
})
}

You can try this control. Its is pretty neat. DZNEmptyDataSet
Or if I were you all I would do is
Check to see if your data array is empty
If it is empty then add one object called #"No Data" to it
Display that string in cell.textLabel.text
Easy peasy

Swift 3 (updated):
override func numberOfSections(in tableView: UITableView) -> Int {
if myArray.count > 0 {
self.tableView.backgroundView = nil
self.tableView.separatorStyle = .singleLine
return 1
}
let rect = CGRect(x: 0,
y: 0,
width: self.tableView.bounds.size.width,
height: self.tableView.bounds.size.height)
let noDataLabel: UILabel = UILabel(frame: rect)
noDataLabel.text = "Custom message."
noDataLabel.textColor = UIColor.white
noDataLabel.textAlignment = NSTextAlignment.center
self.tableView.backgroundView = noDataLabel
self.tableView.separatorStyle = .none
return 0
}

Swift3.0
I hope it server your purpose......
In your UITableViewController .
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.isActive && searchController.searchBar.text != "" {
if filteredContacts.count > 0 {
self.tableView.backgroundView = .none;
return filteredContacts.count
} else {
Helper.EmptyMessage(message: ConstantMap.NO_CONTACT_FOUND, viewController: self)
return 0
}
} else {
if contacts.count > 0 {
self.tableView.backgroundView = .none;
return contacts.count
} else {
Helper.EmptyMessage(message: ConstantMap.NO_CONTACT_FOUND, viewController: self)
return 0
}
}
}
Helper Class with function :
/* Description: This function generate alert dialog for empty message by passing message and
associated viewcontroller for that function
- Parameters:
- message: message that require for empty alert message
- viewController: selected viewcontroller at that time
*/
static func EmptyMessage(message:String, viewController:UITableViewController) {
let messageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: viewController.view.bounds.size.width, height: viewController.view.bounds.size.height))
messageLabel.text = message
let bubbleColor = UIColor(red: CGFloat(57)/255, green: CGFloat(81)/255, blue: CGFloat(104)/255, alpha :1)
messageLabel.textColor = bubbleColor
messageLabel.numberOfLines = 0;
messageLabel.textAlignment = .center;
messageLabel.font = UIFont(name: "TrebuchetMS", size: 18)
messageLabel.sizeToFit()
viewController.tableView.backgroundView = messageLabel;
viewController.tableView.separatorStyle = .none;
}

I think the most elegant way to solve your problem is switching from a UITableViewController to a UIViewController that contains a UITableView. This way you can add whatever UIView you want as subviews of the main view.
I wouldn't recommend using a UITableViewCell to do this you might need to add additional things in the future and things can quicky get ugly.
You can also do something like this, but this isn't the best solution either.
UIWindow* window = [[UIApplication sharedApplication] keyWindow];
[window addSubview: OverlayView];

Use this code in Your numberOfSectionsInTableView method:-
if ([array count]==0
{
UILabel *fromLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, self.view.frame.size.height/2, 300, 60)];
fromLabel.text =#"No Result";
fromLabel.baselineAdjustment = UIBaselineAdjustmentAlignBaselines;
fromLabel.backgroundColor = [UIColor clearColor];
fromLabel.textColor = [UIColor lightGrayColor];
fromLabel.textAlignment = NSTextAlignmentLeft;
[fromLabel setFont:[UIFont fontWithName:Embrima size:30.0f]];
[self.view addSubview:fromLabel];
[self.tblView setHidden:YES];
}

I would present a an overlay view that has the look and message you want if the tableview has no results. You could do it in ViewDidAppear, so you have the results before showing/not showing the view.

SWIFT 3
let noDataLabel: UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: tableView.bounds.size.height))
noDataLabel.text = "No data available"
noDataLabel.textColor = UIColor.white
noDataLabel.font = UIFont(name: "Open Sans", size: 15)
noDataLabel.textAlignment = .center
tableView.backgroundView = noDataLabel
tableView.separatorStyle = .none

If you don't use the tableview footer and do not want the tableview to fill up the screen with empty default table cells i would suggest that you set your tableview footer to an empty UIView. I do not know the correct syntax for doing this in obj-c or Swift, but in Xamarin.iOS i would do it like this:
public class ViewController : UIViewController
{
UITableView _table;
public ViewController (IntPtr handle) : base (handle)
{
}
public override void ViewWillAppear(bool animated) {
// Initialize table
_table.TableFooterView = new UIView();
}
}
Above code will result in a tableview without the empty cells

Here is the solution that worked for me.
Add the following code to a new file.
Change your table class to the custom class "MyTableView" from storyboard or .xib
(this will work for the first section only. If you want to customize more, do changes in the MyTableView reloadData() function accordingly for other sections)
public class MyTableView: UITableView {
override public func reloadData() {
super.reloadData()
if self.numberOfRows(inSection: 0) == 0 {
if self.viewWithTag(1111) == nil {
let noDataLabel = UILabel()
noDataLabel.textAlignment = .center
noDataLabel.text = "No Data Available"
noDataLabel.tag = 1111
noDataLabel.center = self.center
self.backgroundView = noDataLabel
}
} else {
if self.viewWithTag(1111) != nil {
self.backgroundView = nil
}
}
}
}

If you want to do this without any code, try this!
Click on your tableView.
Change the style from "plain" to "grouped".
Now when you use ....
tableView.backgroundView = INSERT YOUR LABEL OR VIEW
It will not show the separators!

Add this code in one file and change your collection type to CustomCollectionView
import Foundation
class CustomCollectionView: UICollectionView {
var emptyModel = EmptyMessageModel()
var emptyView: EmptyMessageView?
var showEmptyView: Bool = true
override func reloadData() {
super.reloadData()
emptyView?.removeFromSuperview()
self.backgroundView = nil
if !showEmptyView {
return
}
if numberOfSections < 1 {
let rect = CGRect(x: 0,
y: 0,
width: self.bounds.size.width,
height: self.bounds.size.height)
emptyView = EmptyMessageView()
emptyView?.frame = rect
if let emptyView = emptyView {
// self.addSubview(emptyView)
self.backgroundView = emptyView
}
emptyView?.setView(with: emptyModel)
} else {
emptyView?.removeFromSuperview()
self.backgroundView = nil
}
}
}
class EmptyMessageView: UIView {
#IBOutlet weak var messageLabel: UILabel!
#IBOutlet weak var imageView: UIImageView!
var view: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
func xibSetup() {
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(view)
}
func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "EmptyMessageView", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
return view
}
func setView(with model: EmptyMessageModel) {
messageLabel.text = model.message ?? ""
imageView.image = model.image ?? #imageLiteral(resourceName: "no_notification")
}
}
///////////
class EmptyMessageModel {
var message: String?
var image: UIImage?
init(message: String = "No data available", image: UIImage = #imageLiteral(resourceName: "no_notification")) {
self.message = message
self.image = image
}
}

Related

Align label's center.x with image inside tabBar's imageView

I need to get a label's center.x directly aligned with the image inside a tabBar's imageView. Using the below code the label is misaligned, instead of the label's text "123" being directly over the bell inside the tabBar, it's off to the right.
guard let keyWindow = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) else { return }
guard let fourthTab = tabBarController?.tabBar.items?[3].value(forKey: "view") as? UIView else { return }
guard let imageView = fourthTab.subviews.compactMap({ $0 as? UIImageView }).first else { return }
guard let imageViewRectInWindow = imageView.superview?.superview?.convert(fourthTab.frame, to: keyWindow) else { return }
let imageRect = AVMakeRect(aspectRatio: imageView.image!.size, insideRect: imageViewRectInWindow)
myLabel.text = "123"
myLabel.textAlignment = .center // I also tried .left
myLabel.center.x = imageRect.midX
myLabel.center.y = UIScreen.main.bounds.height - 74
myLabel.frame.size.width = 50
myLabel.frame.size.height = 21
print("imageViewRectInWindow: \(imageViewRectInWindow)") // (249.99999999403948, 688.0, 79.00000000298022, 48.0)
print("imageRect: \(imageRect)") // (265.4999999955296, 688.0, 48.0, 48.0)
print("myLabelRect: \(myLabel.frame)") // (289.4999999955296, 662.0, 50.0, 21.0)
It might be a layout issue, as in, setting the coordinates before everything is laid out. Where do you call the code from? I was able to get it to work with the following, but got strange results with some if the functions you use, so cut out a couple of them. Using the frame of the tabview worked for me, and calling the coordinate setting from the view controller's viewDidLayoutSubviews function.
class ViewController: UIViewController {
var myLabel: UILabel = UILabel()
var secondTab: UIView?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.addSubview(myLabel)
myLabel.textColor = .black
myLabel.text = "123"
myLabel.textAlignment = .center // I also tried .left
myLabel.frame.size.width = 50
myLabel.frame.size.height = 21
secondTab = tabBarController?.tabBar.items?[1].value(forKey: "view") as? UIView
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
guard let secondTab = secondTab else {
return
}
myLabel.center.x = secondTab.frame.midX
myLabel.center.y = UIScreen.main.bounds.height - 70
}
}
Try below code to return a centreX by tabbar item index.
extension UIViewController {
func centerX(of tabItemIndex: Int) -> CGFloat? {
guard let tabBarItemCount = tabBarController?.tabBar.items?.count else { return nil }
let itemWidth = view.bounds.width / CGFloat(tabBarItemCount)
return itemWidth * CGFloat(tabItemIndex + 1) - itemWidth / 2
}
}

iOS UITableView is not selectable when it is scrolled

I am facing this issue and I am not getting any clear answer. I have a UITableView which works fine when it loads for the first time but when it scrolls, it is not selectable, didSelectRowAtIndexPath never gets a call. Also I've button in my cell, it's not clickable either. But I can still scroll tableview. This is my code :
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell : ContactTableViewCell = tableView.dequeueReusableCell(withIdentifier: "ContactCell") as! ContactTableViewCell
cell.selectionStyle = .none
cell.backgroundColor = UIColor.clear
cell.delegate = self
let randomNumber = Int(arc4random_uniform(UInt32(colorsArray!.count)))
if(!shouldUseFilteredResults) {
cell.setFilteredContents(_with: addressBookArray![indexPath.row], theme: themeStyle!, randomColor: colorsArray![randomNumber])
}
else {
cell.setFilteredContents(_with: filteredAddressBook[indexPath.row], theme: themeStyle!, randomColor: colorsArray![randomNumber])
cell.contactNameLabel.attributedText = self.highlightSearchResult(resultString: cell.contactNameLabel.text!)
}
return cell
}
In cell :
public func setFilteredContents (_with contact : [String : Any], theme : Theme, randomColor : UIColor)
{
contactDictionary = contact;
contactNameLabel.text = String(describing: contact["FullName"]!)
self.setTheme(theme: theme, randomColor: randomColor)
if (contact["ImageDataString"] != nil)
{
let imageData = Data(base64Encoded: contact["ImageDataString"] as! String)
let image = UIImage(data: imageData!)
let imageView = UIImageView(frame: thumbnailView.bounds)
imageView.contentMode = .scaleAspectFill
imageView.layer.masksToBounds = true
imageView.layer.cornerRadius = CGFloat(imageView.height()/2)
imageView.image = image
thumbnailView.addSubview(imageView)
}
else {
self.setThumbnail(fullName: contactNameLabel.text!)
}
}
private func setThumbnail(fullName : String)
{
let vibrancy = UIVibrancyEffect(blurEffect: UIBlurEffect(style: .light))
let backgroundView = UIVisualEffectView(effect: vibrancy)
backgroundView.frame = thumbnailView.bounds
thumbnailView.addSubview(backgroundView)
let thumbNailLabel = UILabel(frame: thumbnailView.bounds)
thumbNailLabel.font = UIFont.systemFont(ofSize: 13)
thumbNailLabel.textColor = UIColor.white
thumbNailLabel.textAlignment = .center
var initialLettersString = String()
let wordsArray = fullName.components(separatedBy: NSCharacterSet.whitespaces)
for word in wordsArray
{
if(word != "")
{
initialLettersString.append(String(describing: word.characters.first!))
}
}
if(initialLettersString.characters.count == 1)
{
initialLettersString = String(initialLettersString[..<initialLettersString.index(initialLettersString.startIndex, offsetBy: 1)]).uppercased()
}
if(initialLettersString.characters.count > 1)
{
initialLettersString = String(initialLettersString[..<initialLettersString.index(initialLettersString.startIndex, offsetBy: 2)]).uppercased()
}
thumbNailLabel.text = initialLettersString as String
backgroundView.contentView.addSubview(thumbNailLabel)
}
private func setTheme(theme : Theme, randomColor : UIColor)
{
let isContactFavorite = contactDictionary?[Constants.TTCIsContactFavoriteKey] as? Bool
thumbnailView.backgroundColor = randomColor
if(theme == Theme.Light)
{
contactNameLabel.textColor = UIColor.black
lineView.backgroundColor = UIColor.lightGray
if(!isContactFavorite!)
{
favoritesButton.setImage(UIImage(named: "favorite_dark.png"), for: .normal)
}
else
{
favoritesButton.setImage(UIImage(named: "favorite.png"), for: .normal)
}
}
else if(theme == Theme.Dark)
{
contactNameLabel.textColor = UIColor.white
lineView.backgroundColor = UIColor.gray
if(!isContactFavorite!)
{
favoritesButton.setImage(UIImage(named: "favorite_white.png"), for: .normal)
}
else
{
favoritesButton.setImage(UIImage(named: "favorite.png"), for: .normal)
}
}
for view in thumbnailView.subviews
{
view.removeFromSuperview()
}
}
Custom Cell :
What could be the issue?
This may also because of overriding default touch events with UITapRecognizers in the View Hierarchy
Remove any tap recognizers set to to UITableview Parent View
Thanks everyone for help. Issue was with SwipeCellKit which I was using for CustomCell. Removing it solved it!
You are doing everything right.
Just check your button frame does lies inside your cell.
Some times your cell height is less and button is outside the bounds of cell.

how to prevent cell reuse of uicollectionview

I use UICollectionView and refer to this link implement scroll table view Fixed single column and row like below image.
but when I want to add shadow property, it display messy.
I think the reason is that I reuse cell when render visual view, but I don't know how to fix it :(
provide my code below, thanks for your time!
import Foundation
import SwiftyJSON
#objc(RNCollection)
class RNCollection : UICollectionView, UICollectionViewDataSource, UICollectionViewDelegate {
var contentCellIdentifier = "CellIdentifier"
var collectionView: UICollectionView!
static var dataSource = []
static var sections = 0
static var rows = 0
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: CGRectZero, collectionViewLayout: RNCollectionLayout())
self.registerClass(RNCollectionCell.self, forCellWithReuseIdentifier: contentCellIdentifier)
self.directionalLockEnabled = false
self.backgroundColor = UIColor.whiteColor()
self.delegate = self
self.dataSource = self
self.frame = frame
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setConfig(config: String!) {
var json: JSON = nil;
if let data = config.dataUsingEncoding(NSUTF8StringEncoding) {
json = JSON(data: data);
};
RNCollection.dataSource = json["dataSource"].arrayObject!
RNCollection.sections = json["sections"].intValue
RNCollection.rows = json["rows"].intValue
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let contentCell: RNCollectionCell = collectionView.dequeueReusableCellWithReuseIdentifier(contentCellIdentifier, forIndexPath: indexPath) as! RNCollectionCell
contentCell.textLabel.textColor = UIColor.blackColor()
if indexPath.section == 0 {
contentCell.backgroundColor = UIColor(red: 232/255.0, green: 232/255.0, blue: 232/255.0, alpha: 1.0)
if indexPath.row == 0 {
contentCell.textLabel.font = UIFont.systemFontOfSize(16)
contentCell.textLabel.text = (RNCollection.dataSource[0] as! NSArray)[0] as? String
} else {
contentCell.textLabel.font = UIFont.systemFontOfSize(14)
contentCell.textLabel.text = (RNCollection.dataSource[0] as! NSArray)[indexPath.row] as? String
}
} else {
contentCell.textLabel.font = UIFont.systemFontOfSize(12)
contentCell.backgroundColor = UIColor.whiteColor()
if(indexPath.section % 2 == 0) {
contentCell.backgroundColor = UIColor(red: 234/255.0, green: 234/255.0, blue: 236/255.0, alpha: 1.0)
}
if indexPath.row == 0 {
contentCell.textLabel.text = (RNCollection.dataSource[indexPath.section] as! NSArray)[0] as? String
contentCell.layer.shadowOffset = CGSize(width: 3, height: 3)
contentCell.layer.shadowOpacity = 0.7
contentCell.layer.shadowRadius = 2
} else {
contentCell.textLabel.text = (RNCollection.dataSource[indexPath.section] as! NSArray)[indexPath.row] as? String
}
}
return contentCell
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return RNCollection.rows
}
// MARK - UICollectionViewDataSource
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return RNCollection.sections
}
}
You are specifying your customizations for a certain section/row and in your else condition you just set the text. You should specify your required/default customization in your else condition. Consider this part of your code
if indexPath.row == 0 {
contentCell.textLabel.text = (RNCollection.dataSource[indexPath.section] as! NSArray)[0] as? String
contentCell.layer.shadowOffset = CGSize(width: 3, height: 3)
contentCell.layer.shadowOpacity = 0.7
contentCell.layer.shadowRadius = 2
} else {
contentCell.textLabel.text = (RNCollection.dataSource[indexPath.section] as! NSArray)[indexPath.row] as? String
}
You have specified your shadowOffset,shadowOpacity and shadowRadius in your if condition, but you ignored them in your else condition. If you specify the appearance in the else condition you won't have the problem you are facing now. It should look something like this
if indexPath.row == 0 {
contentCell.textLabel.text = (RNCollection.dataSource[indexPath.section] as! NSArray)[0] as? String
contentCell.layer.shadowOffset = CGSize(width: 3, height: 3)
contentCell.layer.shadowOpacity = 0.7
contentCell.layer.shadowRadius = 2
} else {
contentCell.textLabel.text = (RNCollection.dataSource[indexPath.section] as! NSArray)[indexPath.row] as? String
contentCell.layer.shadowOffset = 0
contentCell.layer.shadowOpacity = 0
contentCell.layer.shadowRadius = 0
}
If you reset everything properly in all your condition checks, this problem won't occur.
You set up shadow when your row is equal to 0:
if indexPath.row == 0 {...}
but if the row is not equal to zero collection view can reuse the cell when the shadow was already set. The solution is reset the shadow when row is not 0, in your code you can do something like this (see todo):
if indexPath.row == 0 { // Set up shadow here
contentCell.textLabel.text = (RNCollection.dataSource[indexPath.section] as! NSArray)[0] as? String
contentCell.layer.shadowOffset = CGSize(width: 3, height: 3)
contentCell.layer.shadowOpacity = 0.7
contentCell.layer.shadowRadius = 2
} else {
contentCell.textLabel.text = (RNCollection.dataSource[indexPath.section] as! NSArray)[indexPath.row] as? String
//TODO: Remove the shadow here
}
If you wanna save the cell setting everytime when your cell appears,you should set every possible condition of the method "func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell".Do not prevent the reuse of collectionView only if your data or items is few.
In Objective-C, but in Swift, the logic should be the same and not that hard to translate.
In RNCollectionCell.
//These enums may have a better nam, I agree
typedef enum : NSUInteger {
RNCollectionCellStyleColumnTitle,
RNCollectionCellStyleColumnValue,
RNCollectionCellStyleRowTitle,
RNCollectionCellStyleUpperLeftCorner,
} RNCollectionCellStyle;
-(void)titleIt:(NSString *)title forStyle:(RNCollectionCellStyle)style forSection:(NSUInteger)section
{
self.textLabel.textColor = [UIColor blackColor]; //Since it's always the same could be done elsewhere once for all.
//Note I didn't check completely if the case were good, and I didn't add the background color logic, but it should be done here too.
switch (style)
{
case RNCollectionCellStyleColumnTitle:
{
self.textLabel.font = [UIFont systemFontOfSize:12];
self.layer.shadowOffset = CGSizeMake(3, 3);
self.layer.shadowOpacity = 0.7;
self.layer.shadowRadius = 2;
}
break;
case RNCollectionCellStyleColumnValue:
{
self.textLabel.font = [UIFont systemFontOfSize:12];
self.layer.shadowOffset = CGSizeZero;
self.layer.shadowOpacity = 0;
self.layer.shadowRadius = 0;
}
break;
case RNCollectionCellStyleRowTitle:
{
self.textLabel.font = [UIFont systemFontOfSize:14];
self.layer.shadowOffset = CGSizeZero;
self.layer.shadowOpacity = 0;
self.layer.shadowRadius = 0;
}
break;
case RNCollectionCellStyleUpperLeftCorner:
{
self.textLabel.font = [UIFont systemFontOfSize:16];
self.layer.shadowOffset = CGSizeZero;
self.layer.shadowOpacity = 0;
self.layer.shadowRadius = 0;
}
break;
default:
break;
}
self.textLabel.text = title;
}
-(void)prepareForReuse
{
[super prepareForReuse];
self.layer.shadowOffset = CGSizeZero;
self.layer.shadowOpacity = 0;
self.layer.shadowRadius = 0;
}
In RNCollection:
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath
{
RNCollectionCell *contentCell = [collectionView dequeueReusableCellWithReuseIdentifier: contentCellIdentifier forIndexPath:indexPath];
//Here check what style you need to do
//Also, you seems to always do dataSource[indexPath.section][indexPath.row], you just use the "if test values".
[contentCell titleIt:dataSource[indexPath.section][indexPath.row]
forStyle:RNCollectionCellStyleColumnTitle
forSection:[indexPath section]];
return contentCell;
}
As said, I didn't check if all the cases were correct according to your needs.
But, you don't "prevent reuse of cell", it's optimized.
You need to "reset" values before reused or when you set the values. In theory the thing done in prepareForReuse should be enough and you shouldn't have to "reset" the layer effect in the switch, but I honestly didn't check it.

I have a UILabel that is visible only when my UITableView is empty. How can I center the text of that label in Swift?

I have a UITableView in my app and I want to present there a UILabel when there is no content. So far I'm doing:
#IBOutlet var tview: UITableView!
var emptyLabel = UILabel(frame: CGRectMake(0, 10, 100, 100))
override func viewDidLoad(){
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: "refresh:", forControlEvents: .ValueChanged)
refreshControl.attributedTitle = NSAttributedString(string: "last updated on \(NSDate())")
tview.separatorStyle = UITableViewCellSeparatorStyle.None
tview.addSubview(refreshControl)
emptyLabel.numberOfLines = 0
emptyLabel.text = "There is no content in this table for now. Please pull down the list to refresh and something should appear"
emptyLabel.font = emptyLabel.font.fontWithSize(10)
tview.backgroundView = emptyLabel
}
But when I do like that, I have the following result:
and instead of the alignment to the left I would like to center the text, so that it looks something like:
There is no content in this table for now. Please pull down the
list to refresh and something should appear
Also, currently it's centered vertically - is there a way of putting this message let's say in 1/3 of the screen from the top?
====== EDIT
#Md.Muzahidul Islam this is how I present the label when the table is empty:
override func tableView(tview: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.items.count == 0{
self.emptyLabel.hidden = false
return 0
} else {
self.emptyLabel.hidden = true
return self.items.count;
}
}
You can achieve this by:
override func viewDidLoad()
{
// Other codes
emptyLabel = UILabel(frame: CGRectMake(0, 0, tview.bounds.size.width, view.bounds.size.height))
emptyLabel.textAlignment = NSTextAlignment.Center
emptyLabel.numberOfLines = 0
emptyLabel.text = "There is no content in this table for now. Please pull down the list to refresh and something should appear"
emptyLabel.font = emptyLabel.font.fontWithSize(10)
tview.backgroundView = emptyLabel
}
You can read more about it here
Swift3.0
I hope it server your purpose......
In your UITableViewController .
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.isActive && searchController.searchBar.text != "" {
if filteredContacts.count > 0 {
self.tableView.backgroundView = .none;
return filteredContacts.count
} else {
Helper.EmptyMessage(message: ConstantMap.NO_CONTACT_FOUND, viewController: self)
return 0
}
} else {
if contacts.count > 0 {
self.tableView.backgroundView = .none;
return contacts.count
} else {
Helper.EmptyMessage(message: ConstantMap.NO_CONTACT_FOUND, viewController: self)
return 0
}
}
}
Helper Class with function :
/* Description: This function generate alert dialog for empty message by passing message and
associated viewcontroller for that function
- Parameters:
- message: message that require for empty alert message
- viewController: selected viewcontroller at that time
*/
static func EmptyMessage(message:String, viewController:UITableViewController) {
let messageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: viewController.view.bounds.size.width, height: viewController.view.bounds.size.height))
messageLabel.text = message
let bubbleColor = UIColor(red: CGFloat(57)/255, green: CGFloat(81)/255, blue: CGFloat(104)/255, alpha :1)
messageLabel.textColor = bubbleColor
messageLabel.numberOfLines = 0;
messageLabel.textAlignment = .center;
messageLabel.font = UIFont(name: "TrebuchetMS", size: 18)
messageLabel.sizeToFit()
viewController.tableView.backgroundView = messageLabel;
viewController.tableView.separatorStyle = .none;
}

Issue with "if" statement: "trying to style message.content differently according to message.sender

I have created a class of message including, content and sender. I successfully store the desired data in Parse and I am querying them. So far, no problem. Then, I attempt to filter the messages according to the sender, or the receiver, in order to display them in different manners on my tableView.
For instance, let's say that is sender is currentUser, the text is blue, otherwise it is green.
If currentUser sends a message, all the text becomes blue, even the one sent by the other user; and vice versa.
class Message {
var sender = ""
var message = ""
var time = NSDate()
init(sender: String, message: String, time: NSDate)
{
self.sender = sender
self.message = message
self.time = time
}
}
var message1: Message = Message(sender: "", message: "", time: NSDate())
func styleTextView()
{
if message1.sender == PFUser.currentUser()?.username {
self.textView.textColor = UIColor.blueColor()
} else {
self.textView.textColor = UIColor.greenColor()
}
}
func addMessageToTextView(message1: Message)
{
textView.text = message1.message
self.styleTextView()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell: messageCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! messageCell
let message = self.array[indexPath.row]
cell.setupWithMessage(message)
return cell
}
I have other codes on my viewController, however I believe they are irrelevant to this matter; if needed, I can provide them.
Any idea why I cannot have the textViews in different style according to the sender?
They are all either blue, either green.
Below is the code for the full set up of the tableViewCell:
class messageCell: UITableViewCell {
private let padding: CGFloat = 10.0
var array1 = [Message]()
private func styleTextView()
{
let halfTextViewWidth = CGRectGetWidth(textView.bounds) / 2.0
let targetX = halfTextViewWidth + padding
let halfTextViewHeight = CGRectGetHeight(textView.bounds) / 2.0
self.textView.font = UIFont.systemFontOfSize(12.0)
if PFUser.currentUser()?.username == message1.sender && textView.text == message1.message {
self.textView.backgroundColor = UIColor.blueColor()
self.textView.layer.borderColor = UIColor.blueColor().CGColor
self.textView.textColor = UIColor.whiteColor()
textView.center.x = targetX
textView.center.y = halfTextViewHeight
} else {
self.textView.backgroundColor = UIColor.orangeColor()
self.textView.layer.borderColor = UIColor.orangeColor().CGColor
self.textView.textColor = UIColor.whiteColor()
self.textView.center.x = CGRectGetWidth(self.bounds) - targetX
self.textView.center.y = halfTextViewHeight
}
}
private lazy var textView: MessageBubbleTextView = {
let textView = MessageBubbleTextView(frame: CGRectZero, textContainer: nil)
self.contentView.addSubview(textView)
return textView
}()
class MessageBubbleTextView: UITextView
{
override init(frame: CGRect = CGRectZero, textContainer: NSTextContainer? = nil)
{
super.init(frame: frame, textContainer: textContainer)
self.scrollEnabled = false
self.editable = false
self.textContainerInset = UIEdgeInsets(top: 7, left: 7, bottom: 7, right: 7)
self.layer.cornerRadius = 15
self.layer.borderWidth = 2.0
}
required init(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
}
private let minimumHeight: CGFloat = 30.0
private var size = CGSizeZero
private var maxSize: CGSize {
get {
let maxWidth = CGRectGetWidth(self.bounds)
let maxHeight = CGFloat.max
return CGSize(width: maxWidth, height: maxHeight)
}
}
func setupWithMessage(message: Message) -> CGSize
{
textView.text = message.message
size = textView.sizeThatFits(maxSize)
if size.height < minimumHeight {
size.height = minimumHeight
}
textView.bounds.size = size
self.styleTextView()
return size
}
}
One possible error can be in this line:
if message1.sender == PFUser.currentUser()?.username
where you are comparing different types since message1 is a String whereas PFUser.currentUser()?.username is an optional String. The right way to compare them is:
if let username = PFUser.currentUser()?.username where username == message1.sender {
self.textView.textColor = UIColor.blueColor()
} else {
self.textView.textColor = UIColor.greenColor()
}
This is because you are changing the text color of the entire UITextView with your code. See the following post for a start in the right direction: Is it possible to change the color of a single word in UITextView and UITextField

Resources