My scrolling, while smooth usually, is jerky sometimes - swift

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

Related

Current date border color is displayed multiple times in JTCalendar in Swift

I am displaying booked dates in grey cell background and the current date in a black border color. I have an issue that the border color that is used to display the current day appears after every three months at the same spot. Kindly how may i solve this? I have tried to look up questions on this issue. I think i have just miss matched my statements. If anyone can see what wrong am doing kindly help me fix this.
public func calendar(_ calendar: JTCalendarManager!, prepareDayView dayView: (UIView & JTCalendarDay)!)
{
let mydayview=dayView as! JTCalendarDayView
if dayView.isFromAnotherMonth(){
dayView.isHidden = true
}
// compareWithCurrentDate(date: mydayview.date)
mydayview.textLabel.font = UIFont(name:"Montserrat-Regular", size:13)
mydayview.circleRatio = 2
//1.5
// cornerradius
mydayview.circleView.layer.cornerRadius = 1
mydayview.isFromAnotherMonth = false
mydayview.textLabel.textColor = UIColor.gray
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd"
let dateStr = dateFormatter.string(from: mydayview.date)
print(dateStr)
if(isAVailableOnSelectedDate(dateStr: dateStr)){
let now = Date()
dateFormatter.dateFormat = "yyyy-MM-dd"
print(dateFormatter.string(from: now))
if let currentDate = calendarManager.date() {
let currentDateString = String(describing: currentDate)
print(currentDateString)
if dateFormatter.string(from: now) == currentDateString.prefix(10){
mydayview.circleView.isHidden = false
mydayview.circleView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)
//1
mydayview.backgroundColor = UIColor.white
mydayview.textLabel.textColor = UIColor.black
}
else{
mydayview.circleView.isHidden = true;
mydayview.backgroundColor = UIColor.white
// mydayview.dotView.backgroundColor = UIColor.red
mydayview.textLabel.textColor = UIColor.gray
}
}
}
else if calendarManager.dateHelper.date(calendarContentView.date, isTheSameMonthThan: mydayview.date)
{
mydayview.circleView.isHidden = true;
mydayview.backgroundColor = UIColor.white
// mydayview.dotView.backgroundColor = UIColor.red
mydayview.textLabel.textColor = UIColor.gray
}
// Another day of the current month
else
{
mydayview.circleView.isHidden = true;
mydayview.backgroundColor = UIColor.white
mydayview.dotView.backgroundColor = UIColor.clear
mydayview.textLabel.textColor = UIColor.lightGray
// mydayview.textLabel.textColor = UIColor.clear
}
//Current day
if calendarManager.dateHelper.date(Date(), isTheSameDayThan: mydayview.date) {
mydayview.circleView.isHidden = false
mydayview.circleView.backgroundColor = UIColor.white
mydayview.layer.borderColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
mydayview.layer.borderWidth = 1
}
else if mydayview.date > Date(){
// mydayview.layer.borderColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
mydayview.circleView.isHidden = true;
mydayview.backgroundColor = UIColor.white
mydayview.dotView.backgroundColor = UIColor.clear
mydayview.textLabel.textColor = UIColor.lightGray
}
}

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

Table View Lag (even after removing gesture recognizers)

Currently, I have a table view that lags when there are multiple cells. When there is only one cell, it performs smoothly; however, when multiple cells are populated, the table view has a slow feeling, sometimes stutters, and is not as smooth. I removed the gesture recognizers and instead changed it to didSelectRowAt, however there is still lag within the cells. Here is the code for the when the cells are loaded :
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if queryComplete == true {
if displayConvo == true {
let cell = tableView.dequeueReusableCell(withIdentifier: "messageCell", for: indexPath as IndexPath) as! messageTableViewCell
cell.profileImage.image = nil
cell.selectionStyle = UITableViewCell.SelectionStyle.none
var convoContent: messagesViewController.Convo
convoContent = convoList[indexPath.row]
convoContent.itemHeroID = "\(String(describing: convoContent.convoID))"
cell.name.heroID = "\(String(describing: convoContent.convoID))"
cell.lastMessage.text = convoContent.lastMessage
cell.backgroundColor = UIColor.clear
cell.postText.text = convoContent.postContent
if convoContent.revealedBool == true {
cell.profileImage.isHidden = false
cell.profileImage.heroID = "\(String(describing: convoContent.convoID))"
cell.name.text = convoContent.name
cell.timer.isHidden = true
if convoContent.profileImage == "nil" || convoContent.profileImage == nil {
let url = URL(string:"https://firebasestorage.googleapis.comasdjfjaisfdji")
let processor = RoundCornerImageProcessor(cornerRadius: cell.profileImage.frame.size.width / 2)
cell.profileImage.kf.setImage(with: url, placeholder: nil, options: [.processor(processor)])
}
else {
let url = URL(string: convoContent.profileImage!)
let processor = RoundCornerImageProcessor(cornerRadius: cell.profileImage.frame.size.width / 2)
cell.profileImage.kf.setImage(with: url, placeholder: nil, options: [.processor(processor)])
}
}
else {
cell.profileImage.isHidden = true
cell.timer.isHidden = false
cell.timer.isUserInteractionEnabled = false
cell.timer.heroID = "\(String(describing: convoContent.convoID))"
let postDuration = convoContent.timeOfDeletion! - Int(convoContent.time!)
let currentTime = Date().timeIntervalSince1970 * 1000
let difference = Int(round(Double(convoContent.timeOfDeletion! - Int(currentTime))))
let date = Date(timeIntervalSinceNow: TimeInterval(difference / 1000))
cell.name.text = String(timeToDelete(date: date as NSDate, numericDates: false))
let amountOfCircleCovered = (Double(((convoContent.timeOfDeletion!) - Int(currentTime))) / Double(postDuration)) * 100
var timerColor: UIColor?
switch amountOfCircleCovered {
case 0..<30:
timerColor = UIColor (red: 252/255, green: 110/255, blue: 81/255, alpha: 1)
case 30..<60:
timerColor = UIColor (red: 255/255, green: 215/255, blue: 0/255, alpha: 1)
case 60..<100:
timerColor = UIColor(red: 26/255, green: 152/255, blue: 252/255, alpha: 1.0)
default:
timerColor = UIColor(red: 26/255, green: 152/255, blue: 252/255, alpha: 1.0)
}
print(amountOfCircleCovered)
cell.timer.models = [ PieSliceModel(value: Double(100 - amountOfCircleCovered), color: UIColor(red: 220/255, green: 220/255, blue: 220/255, alpha: 1)),
PieSliceModel(value: Double(amountOfCircleCovered), color: timerColor!),
]
}
let lastMessageDate = Date(timeIntervalSince1970: TimeInterval(convoContent.timeOfLastMessage! / 1000))
cell.timeOfLastMessage.text = String(timeAgo(date: lastMessageDate as NSDate, numericDates: false))
return cell
}
else {
let cell = tableView.dequeueReusableCell(withIdentifier: "messageCell", for: indexPath as IndexPath) as! messageTableViewCell
cell.lastMessage.text = "No new messages"
return cell
}
}
else {
let cell = tableView.dequeueReusableCell(withIdentifier: "messageCell", for: indexPath as IndexPath) as! messageTableViewCell
print ("loading")
return cell
}
}
Additionally, I have tried moving some of the aspects of the cell so they can be reset each time by putting them in the cell file:
override func awakeFromNib() {
super.awakeFromNib()
profileImage.cornerRadius = profileImage.frame.size.width / 2
profileImage.clipsToBounds = true
profileImage.layer.borderColor = UIColor.white.cgColor
profileImage.layer.borderWidth = 1
timer.innerRadius = 0
timer.outerRadius = timer.frame.width / 2
timer.animDuration = 0.0
timer.referenceAngle = 270
timer.backgroundColor = UIColor.white
postText.layer.zPosition = 1
if !UIAccessibility.isReduceTransparencyEnabled {
glossyView.backgroundColor = .clear
let blurEffect = UIBlurEffect(style: .regular)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
//always fill the view
blurEffectView.frame = self.glossyView.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
glossyView.addSubview(blurEffectView) //if you have more UIViews, use an insertSubview API to place it where needed
} else {
glossyView.backgroundColor = .black
}
timer.selectedOffset = 0
glossyView.clipsToBounds = true
glossyView.cornerRadius = 12.0
glossyView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
messageBackground.clipsToBounds = true
messageBackground.cornerRadius = 12.0
messageBackground.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
// glossyView.roundCornersView(corners: [.topLeft, .topRight], radius: 12.0)
// messageBackground.roundCornersView(corners: [.bottomLeft,.bottomRight], radius: 12.0)
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override func prepareForReuse() {
profileImage.image = nil
timer.isHidden = true
timer.models = []
}
}
And yet, when multiple cells are loaded, the table view still lags. I made sure there are no gesture recognizers as this link suggests and also the images are being loaded using a library so I am not sure why the cells still lag.
Essentially, the UI was dramatically slowing down the performance. I switched out the pie time CA Layer for png images of circles partially filled, and removed all Hero animations. As a result, both the app and tableview became much smoother.

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

Multiple Tableviews on one page for ipad application

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
}