Multiple Tableviews on one page for ipad application - swift

Working on an application right now with what I hope to implement as a dual tableview that splits the users information into two separate tableviews based on the data that they withdraw but I am stuck at the moment. I have been trying to figure a way to do this for a little while now but most of the pages I find on anything close to this aren't exactly what I am looking for. I made sure everything is connected correctly to have the tableview produce the custom cells and that everything has a class but I am still having no tableviewcells' present themselves probably due to this area of code but I am unsure how to progress. Example of where I am is below:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let entityDeckDescription = NSEntityDescription.entityForName("Deck", inManagedObjectContext: context)
var cell = UITableViewCell()
if tableView == otherCardList {
let cell: cardDetails = otherCardList.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! cardDetails
var cardCount = 0
var myDeckCards: DeckCards?
let listed = frc.objectAtIndexPath(indexPath) as! Cards
cell.cardCount.text = ""
let deckCardsSet = listed.cardselections
print("The set of DeckCards for that Card is \(deckCardsSet.count)")
for eachDeckCard in listed.cardselections{
let myDeckCard = eachDeckCard as! DeckCards
if myDeckCard.cardsstored == entityDeckDescription {
// There is already a DeckCard object for this Card and currentDeck
myDeckCards = eachDeckCard as? DeckCards
cardCount = (myDeckCards?.numberSelected!.integerValue)!
if cardCount == 0 {
cell.cardCount.text = ""
} else {
cell.cardCount.text = "" + cardCount.description
}
}
}
switch (listed.cardType) {
case 1:
cell.cardAttack?.text = "*"
cell.cardAttack?.textColor = UIColor.redColor()
cell.cardHealth?.text = "*"
cell.heathLabel?.textColor = UIColor(red: 0x22/255, green: 0x63/255, blue: 0x29/255, alpha: 1.0)
cell.cardHealth?.textColor = UIColor(red: 0x22/255, green: 0x63/255, blue: 0x29/255, alpha: 1.0)
cell.cardType?.text = "Spell"
case 2:
cell.cardAttack?.text = listed.attack.stringValue
cell.heathLabel?.textColor = UIColor.blackColor()
cell.cardHealth?.textColor = UIColor.blackColor()
cell.cardHealth?.text = listed.health.stringValue
cell.cardType?.text = "Weapon"
cell.cardAttack?.text = listed.attack.stringValue
default:
cell.cardAttack?.text = listed.attack.stringValue
cell.heathLabel?.textColor = UIColor(red: 0x22/255, green: 0x63/255, blue: 0x29/255, alpha: 1.0)
cell.cardAttack?.textColor = UIColor.redColor()
cell.cardHealth?.text = listed.health.stringValue
cell.cardHealth?.textColor = UIColor(red: 0x22/255, green: 0x63/255, blue: 0x29/255, alpha: 1.0)
cell.cardType?.text = "Minion"
}
cell.cardName?.text = listed.name as String
cell.cardCost?.text = listed.cost.stringValue
switch (listed.rarity) {
case 1:
cell.cardRarity?.text = "Legendary"
cell.cardRarity?.textColor = UIColor.orangeColor()
case 2:
cell.cardRarity?.text = "Epic"
cell.cardRarity?.textColor = UIColor.purpleColor()
case 3:
cell.cardRarity?.text = "Rare"
cell.cardRarity?.textColor = UIColor.blueColor()
case 4:
cell.cardRarity?.text = "Common"
cell.cardRarity?.textColor = UIColor.grayColor()
default:
cell.cardRarity?.text = "Starter"
cell.cardRarity?.textColor = UIColor.blackColor()
}
switch (listed.cardClass) {
case 1:
cell.cardName?.textColor = UIColor(red: 0xbe/255, green: 0x23/255, blue: 0x0f/255, alpha: 1.0)
case 2:
cell.cardName?.textColor = UIColor.blueColor()
case 3:
cell.cardName?.textColor = UIColor(red: 0x75/255, green: 0x47/255, blue: 0x19/255, alpha: 1.0)
case 4:
cell.cardName?.textColor = UIColor(red: 0xFF/255, green: 0x80/255, blue: 0x00/255, alpha: 1.0)
case 5:
cell.cardName?.textColor = UIColor(red: 0x22/255, green: 0x63/255, blue: 0x29/255, alpha: 1.0)
case 6:
cell.cardName?.textColor = UIColor.brownColor()
case 7:
cell.cardName?.textColor = UIColor(red: 0x5E/255, green: 0x03/255, blue: 0x8F/255, alpha: 1.0)
case 8:
cell.cardName?.textColor = UIColor(red: 0x01/255, green: 0xA9/255, blue: 0xDB/255, alpha: 1.0)
case 9:
cell.cardName?.textColor = UIColor.magentaColor()
default:
cell.cardName?.textColor = UIColor.blackColor()
}
return cell
} else if tableView == classCardList {
let cell: cardDetails = classCardList.dequeueReusableCellWithIdentifier("classcell", forIndexPath: indexPath) as! cardDetails
var cardCount = 0
var myDeckCards: DeckCards?
let listed = classfrc.objectAtIndexPath(indexPath) as! Cards
cell.cardCount.text = ""
let deckCardsSet = listed.cardselections
print("The set of DeckCards for that Card is \(deckCardsSet.count)")
for eachDeckCard in listed.cardselections{
let myDeckCard = eachDeckCard as! DeckCards
if myDeckCard.cardsstored == entityDeckDescription {
// There is already a DeckCard object for this Card and currentDeck
myDeckCards = eachDeckCard as? DeckCards
cardCount = (myDeckCards?.numberSelected!.integerValue)!
if cardCount == 0 {
cell.cardCount.text = ""
} else {
cell.cardCount.text = "" + cardCount.description
}
}
}
switch (listed.cardType) {
case 1:
cell.cardAttack?.text = "*"
cell.cardAttack?.textColor = UIColor.redColor()
cell.cardHealth?.text = "*"
cell.heathLabel?.textColor = UIColor(red: 0x22/255, green: 0x63/255, blue: 0x29/255, alpha: 1.0)
cell.cardHealth?.textColor = UIColor(red: 0x22/255, green: 0x63/255, blue: 0x29/255, alpha: 1.0)
cell.cardType?.text = "Spell"
case 2:
cell.cardAttack?.text = listed.attack.stringValue
cell.heathLabel?.textColor = UIColor.blackColor()
cell.cardHealth?.textColor = UIColor.blackColor()
cell.cardHealth?.text = listed.health.stringValue
cell.cardType?.text = "Weapon"
cell.cardAttack?.text = listed.attack.stringValue
default:
cell.cardAttack?.text = listed.attack.stringValue
cell.heathLabel?.textColor = UIColor(red: 0x22/255, green: 0x63/255, blue: 0x29/255, alpha: 1.0)
cell.cardAttack?.textColor = UIColor.redColor()
cell.cardHealth?.text = listed.health.stringValue
cell.cardHealth?.textColor = UIColor(red: 0x22/255, green: 0x63/255, blue: 0x29/255, alpha: 1.0)
cell.cardType?.text = "Minion"
}
cell.cardName?.text = listed.name as String
cell.cardCost?.text = listed.cost.stringValue
switch (listed.rarity) {
case 1:
cell.cardRarity?.text = "Legendary"
cell.cardRarity?.textColor = UIColor.orangeColor()
case 2:
cell.cardRarity?.text = "Epic"
cell.cardRarity?.textColor = UIColor.purpleColor()
case 3:
cell.cardRarity?.text = "Rare"
cell.cardRarity?.textColor = UIColor.blueColor()
case 4:
cell.cardRarity?.text = "Common"
cell.cardRarity?.textColor = UIColor.grayColor()
default:
cell.cardRarity?.text = "Starter"
cell.cardRarity?.textColor = UIColor.blackColor()
}
switch (listed.cardClass) {
case 1:
cell.cardName?.textColor = UIColor(red: 0xbe/255, green: 0x23/255, blue: 0x0f/255, alpha: 1.0)
case 2:
cell.cardName?.textColor = UIColor.blueColor()
case 3:
cell.cardName?.textColor = UIColor(red: 0x75/255, green: 0x47/255, blue: 0x19/255, alpha: 1.0)
case 4:
cell.cardName?.textColor = UIColor(red: 0xFF/255, green: 0x80/255, blue: 0x00/255, alpha: 1.0)
case 5:
cell.cardName?.textColor = UIColor(red: 0x22/255, green: 0x63/255, blue: 0x29/255, alpha: 1.0)
case 6:
cell.cardName?.textColor = UIColor.brownColor()
case 7:
cell.cardName?.textColor = UIColor(red: 0x5E/255, green: 0x03/255, blue: 0x8F/255, alpha: 1.0)
case 8:
cell.cardName?.textColor = UIColor(red: 0x01/255, green: 0xA9/255, blue: 0xDB/255, alpha: 1.0)
case 9:
cell.cardName?.textColor = UIColor.magentaColor()
default:
cell.cardName?.textColor = UIColor.blackColor()
}
}
return cell
}
I am fairly sure this is the area of the code that is causing the issues but if you guys think it is elsewhere maybe we can figure out where the issue is coming from. I am still new to coding and always learning as best as I can.

You can achieve this with:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var returnCell: UITableViewCell?
if tableView == tableOutletHere {
// initialize cell here
returnCell = cell
}
if tableView == tableOutletHere {
// initialize cell here
returnCell = cell
}
...
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var returnValue: Int = 0
if tableView == tableOutletHere {
returnValue = array1.count
}
if tableView == tableOutletHere {
returnValue = array2.count
}
...
return returnValue
}

Related

How to pass data from UITableView to UIViewController without segue

I need to pass the title of Row in UITableView to my ViewController. I don't have VC in storyboard (I've created it by code). So I can't use segue.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! UITableViewCell
cell.textLabel?.textColor = UIColor(red: 0, green: 122/255, blue: 1, alpha: 1)
cell.textLabel?.tintColor = UIColor(red: 0, green: 122/255, blue: 1, alpha: 1)
var titleOfFood = String()
if searching == true {
titleOfFood = searchedFoods[indexPath.row].title
cell.textLabel?.textColor = UIColor(red: 0, green: 122/255, blue: 1, alpha: 1)
print(titleOfFood)
} else {
titleOfFood = foods[indexPath.row].title
cell.textLabel?.textColor = UIColor(red: 0, green: 122/255, blue: 1, alpha: 1)
print(titleOfFood)
}
let controller = EatenFoodViewController()
let transitionDelegate = SPStorkTransitioningDelegate()
controller.transitioningDelegate = transitionDelegate
controller.modalPresentationStyle = .custom
//controller.delegate = self
transitionDelegate.customHeight = 620
transitionDelegate.showIndicator = false
self.present(controller, animated: true, completion: nil)
}
I need to pass titleOfFood to EatenFoodViewController
You don't need to have a segue to send data to the destination vc , you can simply do
controller.titleOfFood = arr[indexPath.row].title // assuming you have an array of models
OR
controller.titleOfFood = cell.textLabel!.text!
class EatenFoodViewController:UIViewController {
var titleOfFood = ""
}

Navigation Controller. Background color

For one controller I have settings:
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
and
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
var offset = scrollView.contentOffset.y / 150
if offset > 1 {
offset = 1
self.navigationController?.navigationBar.backgroundColor = UIColor(red: 82/255, green: 76/255, blue: 70/255, alpha: offset)
UIApplication.shared.statusBarView?.backgroundColor = UIColor(red: 82/255, green: 76/255, blue: 70/255, alpha: offset)
self.navigationItem.title = name
} else {
self.navigationController?.navigationBar.backgroundColor = UIColor(red: 82/255, green: 76/255, blue: 70/255, alpha: offset)
UIApplication.shared.statusBarView?.backgroundColor = UIColor(red: 82/255, green: 76/255, blue: 70/255, alpha: offset)
self.navigationItem.title = ""
}
}
The main problem is that when i press back button, settings save. In the end i have white NavigationController. How can I make the settings not taken from the last controller?
func makeSearchController() {
searchController = UISearchController(searchResultsController: nil)
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.tintColor = .white
searchController.searchBar.placeholder = "Блюдо или продукт ..."
}
You can reset the navigation controller's color in viewWillDisappear, like this:
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.navigationController?.navigationBar.backgroundColor = UIColor(red: 221/255, green: 221/255, blue: 225/255, alpha: offset) //gray color
UIApplication.shared.statusBarView?.backgroundColor = UIColor(red: 221/255, green: 221/255, blue: 225/255, alpha: offset) //gray color
}

Matching node.fillColor (SKShapeNode)

I have 25 circles on screen each with a random colour that has been generated from the declared colours and each names 'CIRCLE_1', 'CIRCLE_2' etc.
When matching the node.fillColor with the pre-defined colours, only the Yellow returns a value. Everything else remains at 0.
Can't see what I'm doing wrong/missing.
let SDRed = SKColor(red: 255/255, green: 61/255, blue: 61/255, alpha: 1.0)
let SDBlue = SKColor(red: 0/255, green: 175/255, blue: 255/255, alpha: 1.0)
let SDYellow = SKColor(red: 255/255, green: 255/255, blue: 0/255, alpha: 1.0)
let SDOrange = SKColor(red: 255/255, green: 128/255, blue: 0/255, alpha: 1.0)
let SDPink = SKColor(red: 255/255, green: 105/255, blue: 180/255, alpha: 1.0)
let SDGreen = SKColor(red: 144/255, green: 238/255, blue: 144/255, alpha: 1.0)
let SDDodgerBlue = SKColor(red: 30/255, green: 144/255, blue: 255/255, alpha: 1.0)
func checkAllColoursAvailable() -> Bool {
var yellow = 0
var blue = 0
var pink = 0
var green = 0
var red = 0
var orange = 0
enumerateChildNodes(withName: "CIRCLE_*", using:
{ (node, stop) -> Void in
print((node as! SKShapeNode).name!)
let col: SKColor = (node as! SKShapeNode).fillColor
if col == SDYellow {
yellow = yellow + 1
} else if col == SDGreen {
green = green + 1
} else if col == SDDodgerBlue {
blue = blue + 1
} else if col == SDOrange {
orange = orange + 1
} else if col == SDRed {
red = red + 1
} else if col == SDPink {
pink = pink + 1
}
})
if yellow >= 1 && blue >= 1 && green >= 1 && orange >= 1 && red >= 1 && pink >= 1 {
return true
} else {
return false
}
}

How to add "%" to data in ios-chart

chart, here is my code:
private func setChart(pieChartView: PieChartView, values: [Double]) {
var dataEntries: [PieChartDataEntry] = []
let dataPoints = ["Mar","Apr","May"]
for i in 0..<dataPoints.count {
let dataEntry = PieChartDataEntry(value: values[i], label: dataPoints[i])
dataEntries.append(dataEntry)
}
let pieChartDataSet = PieChartDataSet(values: dataEntries, label: "")
pieChartDataSet.colors = [UIColor(red: 47/255, green: 164/255, blue: 59/255, alpha: 1.0),UIColor(red: 17/255, green: 128/255, blue: 127/255, alpha: 1.0),UIColor.orange]
let pieChartData = PieChartData(dataSet: pieChartDataSet)
pieChartView.data = pieChartData
pieChartView.centerText = "Amount Spent"
pieChartView.chartDescription?.text = ""
pieChartView.usePercentValuesEnabled = true
pieChartView.legend.horizontalAlignment = .center
}
How to add "%" in PieChart data ?
NSNumberFormatter() is no longer available
---------------SOLUTION---------------
I post this solution for everyone who have same problem.
I got it from chart-ios githup :
private func setChart(pieChartView: PieChartView, values: [Double]) {
var dataEntries = [ChartDataEntry]()
let dataPoints = ["Mar","Apr","May"]
for i in 0..<dataPoints.count {
let dataEntry = PieChartDataEntry(value: values[i], label: dataPoints[i])
dataEntries.append(dataEntry)
}
let pieChartDataSet = PieChartDataSet(values: dataEntries, label: "")
let green = UIColor(red: 47/255, green: 164/255, blue: 59/255, alpha: 1.0)
let blue = UIColor(red: 17/255, green: 128/255, blue: 127/255, alpha: 1.0)
pieChartDataSet.colors = [green, blue, .orange]
let pieChartData = PieChartData(dataSet: pieChartDataSet)
let formatter = NumberFormatter()
formatter.numberStyle = .percent
formatter.maximumFractionDigits = 2
formatter.multiplier = 1.0
formatter.percentSymbol = "%"
pieChartData.setValueFormatter(DefaultValueFormatter(formatter: formatter))
pieChartView.data = pieChartData
pieChartView.centerText = "Amount Spent"
pieChartView.chartDescription?.text = ""
pieChartView.usePercentValuesEnabled = true
pieChartView.legend.horizontalAlignment = .center
pieChartView.drawEntryLabelsEnabled = false
pieChartView.holeRadiusPercent = 0.55
pieChartView.highlightPerTapEnabled = false
pieChartView.animate(yAxisDuration: 2.0, easingOption: .easeInBack)
}
if you want to add % in in your graph as well as hide/remove 0.0 values from graph : # Swift 3
used below lines of code:-
func updateChartData() {
let chart = PieChartView(frame: mViewOutlet.frame)
// let chart = PieChartView(frame: CGRect(x: 122, y: 235 , width: self.mViewOutlet.frame.size.width, height: self.mViewOutlet.frame.size.height))
// 2. generate chart data entries
let track = ["Present","Leave", "EG/LC", "Halfday", "Absent", "Weeklyoff", "Holidays"]
// let money = [65, 13, 10, 2]
let money = mDaysArray
var entries = [PieChartDataEntry]()
for (index, value) in money.enumerated() {
print("index: \(index) \n value: \(value)")
let entry = PieChartDataEntry()
if value != 0 {
entry.y = Double(value)
}else{
}
entries.append(entry)
// entry.label = track[index] // if we want to remove name label
}
// 3. chart setup
let set = PieChartDataSet( values: entries, label: "Pie Chart")
// this is custom extension method. Download the code for more details.
//4. set chart color
let presentColor = UIColor(red: 80.0/255.0, green: 180.0/255.0, blue: 50.0/255.0, alpha: 1.0)
// let lateColor = UIColor(red: 241.0/255.0, green: 194.0/255.0, blue: 114.0/255.0, alpha: 1.0)
let leaveColor = UIColor(red: 203.0/255.0, green: 68.0/255.0, blue: 242.0/255.0, alpha: 1.0)
let egColor = UIColor(red: 95.0/255.0, green: 180.0/255.0, blue: 239.0/255.0, alpha: 1.0)
let halfdayColor = UIColor(red: 82.0/255.0, green: 64.0/255.0, blue: 152.0/255.0, alpha: 1.0)
let absentColor = UIColor(red: 242.0/255.0, green: 58.0/255.0, blue: 02.0/255.0, alpha: 1.0)
let weekOffColor = UIColor(red: 186.0/255.0, green: 221.0/255.0, blue: 79.0/255.0, alpha: 1.0)
let holidayColor = UIColor(red: 35.0/255.0, green: 215.0/255.0, blue: 179.0/255.0, alpha: 1.0)
let colors: [UIColor] = [presentColor,leaveColor,egColor,halfdayColor,absentColor,weekOffColor,holidayColor]
set.colors = colors
let data = PieChartData(dataSet: set)
let formatter = NumberFormatter()
formatter.numberStyle = .percent
formatter.maximumFractionDigits = 2
formatter.multiplier = 1.0
formatter.percentSymbol = "%"
formatter.zeroSymbol = ""
data.setValueFormatter(DefaultValueFormatter(formatter: formatter))
chart.data = data
chart.noDataText = "No data available"
chart.usePercentValuesEnabled = true
// user interaction
chart.isUserInteractionEnabled = false
let d = Description()
// d.text = "iOSCharts.io"
chart.chartDescription = d
// chart.tintColor = UIColor.black
// chart.centerText = "Pie Chart"
chart.holeRadiusPercent = 0.2
chart.chartDescription?.enabled = false
chart.legend.enabled = false
chart.data?.notifyDataChanged()
chart.notifyDataSetChanged()
chart.setNeedsDisplay()
chart.animate(xAxisDuration: 1.3, yAxisDuration: 1.3)
chart.transparentCircleColor = UIColor.clear
// self.view.addSubview(chart)
self.mPieChartMainView.addSubview(chart)
}
Please refer below code, i have added %.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var pieChartView: PieChartView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
let unitsSold = [20.0, 4.0, 6.0, 3.0, 12.0, 16.0]
setChart(months, values: unitsSold)
}
func setChart(dataPoints: [String], values: [Double]) {
var dataEntries: [ChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = ChartDataEntry(value: values[i], xIndex: i)
dataEntries.append(dataEntry)
}
let pieChartDataSet = PieChartDataSet(yVals: dataEntries, label: "Units Sold")
let formatter = NSNumberFormatter()
formatter.numberStyle = .PercentStyle
formatter.maximumFractionDigits = 1
formatter.multiplier = 1.0
let pieChartData = PieChartData(xVals: dataPoints, dataSet: pieChartDataSet)
pieChartData.dataSet?.valueFormatter = formatter
pieChartView.data = pieChartData
pieChartView.holeColor = UIColor.clearColor()
// pieChartView.holeRadiusPercent = 0.95
pieChartView.centerText = "Hello\nThis is Pie chart"
pieChartView.usePercentValuesEnabled = true
var colors: [UIColor] = []
for i in 0..<dataPoints.count {
let red = Double(arc4random_uniform(255))
let green = Double(arc4random_uniform(255))
let blue = Double(arc4random_uniform(255))
let color = UIColor(red: CGFloat(red/255), green: CGFloat(green/255), blue: CGFloat(blue/255), alpha: 1)
colors.append(color)
}
pieChartDataSet.colors = colors
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

My scrolling, while smooth usually, is jerky sometimes

The following is my code. I read using NSDateFormatters were expensive, but I'm not sure if that's what's eventually causing the problem.
Here's my code.
func tableViewOld(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!, object: PFObject!) -> UITableViewCell! {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell
if cell.backgroundView == nil {
cell.backgroundView = UIImageView(frame: cell.contentView.bounds)
cell.backgroundView?.contentMode = UIViewContentMode.ScaleToFill
cell.backgroundView?.clipsToBounds = true
cell.contentView.backgroundColor = UIColor.clearColor()
}
let backgroundImageView = cell.backgroundView as! UIImageView
backgroundImageView.image = UIImage(named: "nobg")
var image : UIImage = UIImage(named:"goodbg")!
cell.nopebutton.tag = indexPath.row
cell.nicebutton.tag = indexPath.row
cell.messageButton.tag = indexPath.row
cell.mText.text = object.valueForKey("text") as? String
let count = object.valueForKey("replies") as! Int
cell.replies.text = "\(count)"
cell.replies.textColor = UIColor.whiteColor()
let point = object["location"] as! PFGeoPoint
let location = CLLocation(latitude: point.latitude, longitude: point.longitude)
let currentLocation = CLLocation(latitude: currLocation!.latitude, longitude: currLocation!.longitude)
let distance = currentLocation.distanceFromLocation(location)
if distance < 50 {
// TODO: Fill
cell.locationButton.text = "Nearby"
} else {
let distanceFormatter = MKDistanceFormatter()
distanceFormatter.unitStyle = MKDistanceFormatterUnitStyle.Abbreviated
cell.locationButton.text = distanceFormatter.stringFromDistance(distance) + " away"
}
cell.layoutMargins = UIEdgeInsetsZero
let score = object.valueForKey("count") as! Int
cell.count.text = "\(score)"
if cell.count.text?.toInt() == 0
{
cell.messages.imageView?.image = UIImage(named:"0")
cell.chatbubble.image = UIImage(named:"ch")
cell.bg.image = UIImage(named: "regular")
cell.locationButton.textColor = UIColor.blackColor()
cell.mText.textColor = UIColor(red: 126.0/255, green: 126.0/255, blue: 126.0/255, alpha: 1)
cell.nicebutton!.setImage(UIImage(named:"ups"), forState: UIControlState.Normal)
cell.nopebutton!.setImage(UIImage(named:"downs"), forState: UIControlState.Normal)
cell.count.textColor = UIColor.whiteColor()
cell.time.textColor = UIColor(red: 52.0/255, green: 152.0/255, blue: 219.0/255, alpha: 1)
}
if cell.count.text?.toInt() > 0
{
cell.messages.imageView?.image = UIImage(named:"1")
cell.chatbubble.image = UIImage(named:"chg")
cell.bg.image = UIImage(named: "gtrl")
cell.time.textColor = UIColor(red: 42.0/255, green: 204.0/255, blue: 113.0/255, alpha: 1)
cell.locationButton.textColor = UIColor.blackColor()
cell.mText.textColor = UIColor(red: 42.0/255, green: 204.0/255, blue: 113.0/255, alpha: 1)
cell.count.textColor = UIColor.whiteColor()
}
if cell.count.text?.toInt() < 0
{
cell.messages.imageView?.image = UIImage(named:"-1")
cell.bg.image = UIImage(named: "ntrl")
cell.chatbubble.image = UIImage(named:"chr")
cell.locationButton.textColor = UIColor.blackColor()
cell.time.textColor = UIColor(red: 231.0/255, green: 76.0/255, blue: 50.0/255, alpha: 1)
cell.mText.textColor = UIColor(red: 231.0/255, green: 76.0/255, blue: 50.0/255, alpha: 1)
cell.count.textColor = UIColor.whiteColor()
}
if cell.count.text?.toInt() >= 100
{
cell.messages.imageView?.image = UIImage(named:"100")
cell.chatbubble.image = UIImage(named:"chb")
cell.locationButton.textColor = UIColor.blackColor()
cell.time.textColor = UIColor(red: 249.0/255, green: 194.0/255, blue: 65.0/255, alpha: 1)
cell.mText.textColor = UIColor(red: 249.0/255, green: 194.0/255, blue: 65.0/255, alpha: 1)
cell.bg.image = UIImage(named: "neutral")
cell.count.textColor = UIColor.whiteColor()
}
if let dict : NSDictionary = NSUserDefaults.standardUserDefaults().objectForKey("userNiceNopeDictionary") as? NSDictionary {
cell.nicebutton.enabled = true
cell.nopebutton.enabled = true
if let nice = dict[object.objectId] as? Bool{
if nice {
cell.nicebutton.enabled = false
}
else {
cell.nopebutton.enabled = false
}
}
}
if let user = PFUser.currentUser() {
user["createdBy"] = user.username
//user.saveInBackground()
}
let dateUpdated = object.createdAt as NSDate
let dateFormat = NSDateFormatter()
dateFormat.dateFormat = "h:mm a"
cell.time.text = (NSString(format: "%#", dateFormat.stringFromDate(dateUpdated)) as String) as String
let replycnt = object.objectForKey("replies") as! Int
if cell.count.text == "\(-10)"
{
object.deleteInBackground()
}
return cell
}
and I'm utilizing this extension.
extension NSDate
{
func hour() -> Int
{
//Get Hour
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour, fromDate: self)
let hour = components.hour
//Return Hour
return hour
}
func minute() -> Int
{
//Get Minute
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitMinute, fromDate: self)
let minute = components.minute
//Return Minute
return minute
}
func toShortTimeString() -> String
{
//Get Short Time String
let formatter = NSDateFormatter()
formatter.timeStyle = .ShortStyle
let timeString = formatter.stringFromDate(self)
//Return Short Time String
return timeString
}
}
Is there a way I can optimize this? Again this isn't constantly laggy, it only happens sometimes, but in general it seems to be fine. I'd like to to ALWAYS be fine. Again I feel as though the NSDateFormatter might be the problem, but I'm not quite sure.
You're doing a hell of a lot in the cellForRow method. As a comparison my cellForRow method consists of around 5 lines of code. You should look at creating a custom cell class that removes a lot of that code. With a lot of code it just makes it harder to work out what the cause of problems is.
Each section of that code configures textfields could be a new function. Just, aim for like 10 lines of code per function. If you have more, move stuff into a new function (that makes sense).
What might be causing the issue is creating the NSDateFormatter every time you use the toShortTimeString method.
In fact, I've just seen that you are creating another NSDateFormatter yourself. Creating NSDateFormatter is an expensive thing to do. You should create one as a property of the TableViewController and use that over and over instead of creating it again and again.
That seems like it could be the issue but your function is too big to read through it all. Work on fixing that too.
Number of lines needed in the function... 3.
1 to dequeue the cell.
1 to call a function to configure the cell
1 to return the cell