Problem using Charts in swift with blinking graph and no chart data available - swift

I'm trying to show a pie chart using cocoapod Charts but I'm basically finding two problems. First of all, when the pie chart is showed for the first time it blinks for a couple of seconds. The chart it's in a tab bar so when I return to it there is no blink.
And secondly it is always showing the text "no chart data available" although the data is show. Please the picture I've attached.
Any suggestion?
import UIKit
import Charts
class PieChartViewController: UIViewController, ChartViewDelegate{
#IBOutlet weak var contenedorView: UIView!
#IBOutlet weak var pieChartView: PieChartView!
var nombres: [String]!
var precios: [Double]!
override func viewDidLoad() {
super.viewDidLoad()
pieChartView.delegate = self
nombres = eventos.devolverNombre()
precios = eventos.devolverPrecios()
//Configuramos el gráfico circular
setChart(dataPoints: nombres, values: precios)
self.pieChartView.noDataText = "Geen"
}
override func viewWillAppear(_ animated: Bool) {
reloadInputViews()
self.pieChartView.noDataText = "Geen"
contenedorView.layer.borderWidth = 2
contenedorView.layer.borderColor = UIColor.white.cgColor
contenedorView.layer.cornerRadius = 10
self.view.aplicarFondoDegradado()
}
func setChart(dataPoints: [String], values: [Double]) {
var dataEntries: [PieChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = PieChartDataEntry(value: Double(i), label: dataPoints[i], data: dataPoints[i] as AnyObject)
if dataEntry != nil {
dataEntries.append(dataEntry)}
}
let chartDataSet = PieChartDataSet(entries: dataEntries, label: "PRECIOS POR EVENTO")
let chartData = PieChartData(dataSet: chartDataSet)
pieChartView.holeColor = UIColor.black
pieChartView.data = chartData
var colors: [UIColor] = []
for i in 0..<dataPoints.count {
let red = Double(arc4random_uniform(256))
let green = Double(arc4random_uniform(256))
let blue = Double(arc4random_uniform(256))
let color = UIColor(red: CGFloat(red/255), green: CGFloat(green/255), blue: CGFloat(blue/255), alpha: 1)
colors.append(color)
}
pieChartView.noDataText = ""
pieChartView.holeRadiusPercent = 0.6
pieChartView.legend.textColor = UIColor.white
pieChartView.legend.font = UIFont.systemFont(ofSize: 12)
pieChartView.drawEntryLabelsEnabled = false
chartDataSet.colors = colors
}
}

Related

How may I solve 'Cannot assign value of type 'CATextLayerAlignmentMode' to type 'String'?

func createNewBubbleParentNode(_ text: String) -> SCNNode {
let billBoardConstraint = SCNBillboardConstraint()
billBoardConstraint.freeAxes = SCNBillboardAxis.Y
let bubble = SCNText(string: text, extrusionDepth: CGFloat(bubbleDepth))
var font = UIFont(name: "Futura", size: 0.15)
bubble.font = font
bubble.alignmentMode = kCAAlignmentCenter
return bubbleNodeParent
}
How can I solve 'Cannot assign value of type 'CATextLayerAlignmentMode' to type 'String' with this type of function?
Thanks for your answers!!
Loïc
All you need to do is to use a value CATextLayerAlignmentMode.center.rawValue. This value is used not only in iOS but also in macOS.
bubble.alignmentMode = CATextLayerAlignmentMode.center.rawValue
Here's a full code version:
import ARKit
class ViewController: UIViewController {
#IBOutlet var sceneView: ARSCNView!
override func viewDidLoad() {
super.viewDidLoad()
sceneView.scene = SCNScene()
let textNode = self.createBubbleNode("SceneKit")
sceneView.scene.rootNode.addChildNode(textNode)
sceneView.session.run(ARWorldTrackingConfiguration())
}
func createBubbleNode(_ text: String) -> SCNNode {
let bubble = SCNText(string: text, extrusionDepth: 0.02)
bubble.font = UIFont(name: "Futura", size: 0.15)
bubble.firstMaterial?.diffuse.contents = UIColor.red
bubble.alignmentMode = CATextLayerAlignmentMode.center.rawValue
let bubbleNode = SCNNode(geometry: bubble)
return bubbleNode
}
}
I think you need to replace kCAAlignmentCenter by CATextLayerAlignmentMode.center.rawValue

Swift / how to get score increases by one each time when user get correct answer?

I am new to Swift. I'm currently learning structure module.
I was asked to create a score that increases 1 point each time the user gets an answer right, but my score ends up increased by 2. I am so confused. Everything else is fine. Can someone help me out please?
My code is below:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var questionLable: UILabel!
#IBOutlet weak var progressBar: UIProgressView!
#IBOutlet weak var trueButton: UIButton!
#IBOutlet weak var falseButton: UIButton!
#IBOutlet weak var scoreLabel: UILabel!
var quizBrain = QuizBrain()
override func viewDidLoad() {
super.viewDidLoad()
progressBar.progress = 0
updatedUI()
}
#IBAction func answerButtonPressed(_ sender: UIButton) {
let userAnswer = sender.currentTitle!
let userGotItRight = quizBrain.checkAnswer(userAnswer)
print(quizBrain.checkAnswer(userAnswer))
if userGotItRight{
UIView.animate(withDuration: 0.2) {
sender.backgroundColor = #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1)
}
UIView.animate(withDuration: 0.2) {
sender.backgroundColor = UIColor.clear
}
}else{
UIView.animate(withDuration: 0.2) {
sender.backgroundColor = #colorLiteral(red: 0.9098039269, green: 0.4784313738, blue: 0.6431372762, alpha: 1)
}
UIView.animate(withDuration: 0.2) {
sender.backgroundColor = UIColor.clear
}
}
quizBrain.nextQuestion()
updatedUI()
}
func updatedUI() {
questionLable.text = quizBrain.getQuestionText()
scoreLabel.text = "Score:\(quizBrain.getScore())"
progressBar.progress = quizBrain.getProgress()
}
}
The next part is Model:
import Foundation
struct QuizBrain {
let quiz = [
Question(q: "A slug's blood is green.", a: "True"),
Question(q: "Approximately one quarter of human bones are in the feet.", a: "True"),
Question(q: "The total surface area of two human lungs is approximately 70 square metres.", a: "True"),
Question(q: "Chocolate affects a dog's heart and nervous system; a few ounces are enough to kill a small dog.", a: "True")
]
var questionNumber = 0
var score = 0
mutating func checkAnswer(_ userAnswer: String) -> Bool {
if userAnswer == quiz[questionNumber].answer{
score += 1
return true
}else{
return false
}
}
mutating func getScore() -> Int {
return score
}
func getQuestionText() -> String {
return quiz[questionNumber].text
}
func getProgress() -> Float {
let progress = Float(questionNumber + 1)/Float(quiz.count)
return progress
}
mutating func nextQuestion(){
if questionNumber + 1 < quiz.count{
questionNumber += 1
}else {
questionNumber = 0
score = 0
}
}
}
Your problem is in these two lines:
let userGotItRight = quizBrain.checkAnswer(userAnswer)
print(quizBrain.checkAnswer(userAnswer))
In the first line, you check the answer to see if it is true. If true, it increments by one, but in the next line, you want to just print the result, but you actually call the checkAnswer again, which increments it one more time.
Perhaps you could change the two lines to look like this:
let userGotItRight = quizBrain.checkAnswer(userAnswer)
print(userGotItRight)

How to create marker in ios-chart

I am looking for marker implementation for line chart. I am using swift 3. all my searches failed, and I need a help.
I went through this steps, but it seems to not working well.
I have two graphs and when I touch on them - there are no action (example bellow).
#IBOutlet weak var modelLineChartView: LineChartView!
#IBOutlet weak var lineChartView: LineChartView!
....
func chartValueSelected(chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
let graphPoint = modelLineChartView.getMarkerPosition(highlight: highlight)
let graphPointt = lineChartView.getMarkerPosition(highlight: highlight)
print(graphPoint.x)
print(graphPointt.x)
}
Please help me, I am stuck.
The reason why the code in the other thread does not work is because the chartValueSelected function is slightly different in swift 3.0 than in older versions. I created a test project and with this code every time you click on a value it is printed out:
import Charts
class ViewController: UIViewController, ChartViewDelegate {
#IBOutlet weak var testLineChartView: LineChartView!
override func viewDidLoad() {
super.viewDidLoad()
testLineChartView.delegate = self
let data = generateLineData()
testLineChartView.data = data
}
func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
print("entry.value \(entry)")
}
func generateLineData() -> LineChartData {
let data: LineChartData = LineChartData()
var entries: [ChartDataEntry] = []
var dataArr: [Int] = []
dataArr.append(10)
dataArr.append(5)
dataArr.append(8)
dataArr.append(12)
dataArr.append(10)
for index in 0..<5 {
entries.append(ChartDataEntry(x: Double(index)+0.5, y: Double(dataArr[index]) ) )
}
let set: LineChartDataSet = LineChartDataSet(values: entries, label: "Label")
set.setCircleColor(UIColor.blue)
set.lineWidth = 1
set.circleRadius = 5
set.drawCircleHoleEnabled = false
set.valueTextColor = UIColor.blue
set.valueFont = UIFont(name: "Verdana", size: 12.0)!
set.drawFilledEnabled = true
set.mode = Charts.LineChartDataSet.Mode.linear
set.axisDependency = Charts.YAxis.AxisDependency.left
data.addDataSet(set)
return data
}
}

3D PieChart using Core Plot in swift

I am trying to design a 3D PieChart using core plot.
So that I have the following code
#IBOutlet weak var pieChartDataLabel: UILabel!
#IBOutlet weak var graphView: CPTGraphHostingView!
var pieItem:Int = 0
var pieChartValueArrayToShow = [AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
let graph = CPTXYGraph(frame: CGRectZero)
graph.title = "PieChart"
graph.paddingLeft = 0
graph.paddingTop = 0
graph.paddingRight = 0
graph.paddingBottom = 0
graph.backgroundColor = UIColor.brownColor().CGColor
let overlayGradient = CPTGradient()
overlayGradient.gradientType = CPTGradientType.Radial
overlayGradient.addColorStop(CPTColor.blackColor().colorWithAlphaComponent(0.0), atPosition: 0.9)
overlayGradient.addColorStop(CPTColor.blackColor().colorWithAlphaComponent(0.4), atPosition: 1.0)
let pie = CPTPieChart()
//pie.borderLineStyle = linestyle
pie.dataSource = self
pie.delegate = self
pie.pieRadius = (self.view.frame.size.width * 0.7)/2
pie.overlayFill = CPTFill(gradient: overlayGradient)
graph.addPlot(pie)
self.graphView.hostedGraph = graph;
// Do any additional setup after loading the view.
}
But I am getting a white color pie chart.
here is the image of my output.
https://drive.google.com/open?id=0B9YZfopxzOv5UG9hQmRjZGVQdzQ
I updated my data source and delegate method.
Yes without overly I am getting this output -
https://drive.google.com/open?id=0B9YZfopxzOv5Uy14NXlQYkJZY1k
func numberOfRecordsForPlot(plot: CPTPlot) -> UInt {
return UInt(pieItem)
}
func numberForPlot(plot: CPTPlot, field fieldEnum: UInt, recordIndex idx: UInt) -> AnyObject? {
return pieChartValueArrayToShow[Int(idx)]
}
func pieChart(plot: CPTPieChart, sliceWasSelectedAtRecordIndex idx: UInt) {
print("dataLabel was selected At Record Index getting called")
self.pieChartDataLabel.text = "Your selected value is \(pieChartValueArrayToShow[Int(idx)])"
}
This is my Prepareforsegue Method where I am assigning the pieChartValueArrayToShow and pieItem
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "ShowPieChart") {
let desinationviewController = segue.destinationViewController as! PieChartViewController
let count = pieChartValueArray.count as Int
print(count)
desinationviewController.pieItem = count//(sender?.integerValue)!//pieChartValueArray.count//
print("count is \(pieChartValueArray.count)")
desinationviewController.pieChartValueArrayToShow = pieChartValueArray
}
print("Prepare segue getting called\(sender)")
}
I fixed it by myself. I did a stupid mistake.
Instead of this
overlayGradient.addColorStop(CPTColor.blackColor().colorWithAlphaComponent(0.0), atPosition: 0.9)
overlayGradient.addColorStop(CPTColor.blackColor().colorWithAlphaComponent(0.4), atPosition: 1.0)
I Wrote
overlayGradient = overlayGradient.addColorStop(CPTColor.blackColor().colorWithAlphaComponent(0.0), atPosition: 0.8)
overlayGradient = overlayGradient.addColorStop(CPTColor.blackColor().colorWithAlphaComponent(0.4), atPosition: 1.0)

Segment controller issue

I've got the segment controller above that is connected to the code bellow.
#IBOutlet weak var coatSegmentController: UISegmentedControl!
#IBAction func coatSelectInput() {
switch (self.unitSegmentController.selectedSegmentIndex) {
case 0:
coatSetter = 1
//println("SWITCHED TO coat 1")
println(unitSegmentController.selectedSegmentIndex)
case 1:
coatSetter = 2
//println("SWITCHED TO coat 2")
println(unitSegmentController.selectedSegmentIndex)
case 2:
coatSetter = 3
//println("SWITCHED TO coat 3")
println(unitSegmentController.selectedSegmentIndex)
default:
println("Coat switch did not work")
}
}
No matter what segment I select it always return that I've selected the first segment.
If I hook it to my unit segment outlet it works. But then the unit one stops working.
#IBOutlet weak var unitSegmentController: UISegmentedControl!
Any idea what could that be? I've tried everything. Delete and create again many times. Nothing seems to work.
Here is the full code for the view.
import UIKit
import CoreData
class PaintViewController: UIViewController, UITextFieldDelegate {
//FIELDS *********************************************************
#IBOutlet weak var widthField: UITextField!
#IBOutlet weak var heigthField: UITextField!
#IBOutlet weak var basecoatPriceField: UITextField!
#IBOutlet weak var basecoatCanSizeField: UITextField!
#IBOutlet weak var topcoatPriceField: UITextField!
#IBOutlet weak var topcoatCanSizeField: UITextField!
//FIELD LABELS ***************************************************
#IBOutlet weak var areaToPaintHeader: UILabel!
#IBOutlet weak var basecoatPriceHeader: UILabel!
#IBOutlet weak var topcoatHeader: UILabel!
#IBOutlet weak var basecoatUnit: UILabel!
#IBOutlet weak var topcoatUnit: UILabel!
//RESULT LABELS
#IBOutlet weak var resultBasecoatUnit: UILabel!
#IBOutlet weak var resultBasecoatAmount: UILabel!
#IBOutlet weak var resultBasecoatCost: UILabel!
#IBOutlet weak var resultTopcoatUnit: UILabel!
#IBOutlet weak var resultTopcoatAmount: UILabel!
#IBOutlet weak var resultTopcoatCost: UILabel!
#IBOutlet weak var basecoatNoCostWarning: UILabel!
#IBOutlet weak var topcoatNoCostWarning: UILabel!
// OTHER CONTROLERS
#IBOutlet weak var whatthehell: UISegmentedControl!
#IBOutlet weak var coatSegmentController: UISegmentedControl!
#IBOutlet weak var mainScrollView: UIScrollView!
#IBOutlet weak var unitSegmentController: UISegmentedControl!
// #IBOutlet weak var coatSegController: UISegmentedControl!
// INSTANCES ******************************************************
var unitSetter = "metric"
var coatSetter = 1
//CREATE CONCRETE CORE DATA OBJECT
var paint = [PaintEntity]()
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
// var calculations = PaintModel(
// width: 0.0,
// heigth: 0.0,
// basecoatPrice: 0.0,
// basecoatCanAmount: 0.0,
// topcoatPrice: 0.0,
// topcoatCanAmount: 0.0,
// unit: "metric",
// coats: 1.0)
// ******************************************************************
// NATIVE METHODS
// ******************************************************************
override func viewDidLoad() {
super.viewDidLoad()
//Empty cost warning label
basecoatNoCostWarning.text = ""
topcoatNoCostWarning.text = ""
// RESET CAN
basecoatCanSizeField.text = "5.0"
topcoatCanSizeField.text = "5.0"
// calculations.basecoatCanAmount = 5.0
// calculations.topcoatCanAmount = 5.0
// APPLY ICON
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 31, height: 36))
imageView.contentMode = .ScaleAspectFit
let image = UIImage(named: "concrete_bag_detail")
imageView.image = image
navigationItem.titleView = imageView
// NAV BAR BG CUSTOM ********************
var navBarColor = navigationController!.navigationBar
// BG COLOR
navBarColor.barTintColor = UIColor(hue: 162/360.0, saturation: 80/100.0, brightness: 45/100.0, alpha: 100.0/100.0)
navBarColor.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.blackColor()]
// STATUS BAR WHITE COLOR ********************
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent
// DETECT TAP TO TRIGGER HIDE KEYBOARD
let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "hideKeyboard")
tapGesture.cancelsTouchesInView = false
mainScrollView.addGestureRecognizer(tapGesture)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// ******************************************************************
// MY METHODS
// ******************************************************************
// RESET ******************************************************
// func resetDataModel (){
//
//// calculations.width = 0.0
//// calculations.heigth = 0.0
//// calculations.basecoatPrice = 0.0
//// calculations.basecoatCanAmount = 0.0
//// calculations.topcoatPrice = 0.0
//// calculations.topcoatCanAmount = 0.0
//
// }
func resetInputAndLabels(){
widthField.text = ""
heigthField.text = ""
basecoatPriceField.text = ""
topcoatPriceField.text = ""
basecoatNoCostWarning.text = ""
topcoatNoCostWarning.text = ""
resultBasecoatAmount.text = "0.0"
resultBasecoatCost.text = "$0.00"
resultTopcoatAmount.text = "0.0"
resultTopcoatCost.text = "$0.00"
switch unitSetter {
case "metric":
basecoatCanSizeField.text = "5.0"
topcoatCanSizeField.text = "5.0"
basecoatUnit.text = "litre can"
topcoatUnit.text = "litre can"
resultBasecoatUnit.text = "Litres"
resultTopcoatUnit.text = "Litres"
case "imperial":
basecoatCanSizeField.text = "1.0"
topcoatCanSizeField.text = "1.0"
basecoatUnit.text = "gal can"
topcoatUnit.text = "gal can"
resultBasecoatUnit.text = "Gallons"
resultTopcoatUnit.text = "Gallons"
default:
println("Not able to reset labels")
}
}
//ALERT VIEW METHODS ******************************************************
func alertViewLaunch (#message: String){
var alertView = UIAlertView(title: "Ops!", message: message, delegate: self, cancelButtonTitle: "Ok,got it!")
alertView.show()
}
//KEYBOARD RESIZE VIEW ******************************************
// Call this method somewhere in your view controller setup code.
func registerForKeyboardNotifications() {
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self,
selector: "keyboardWillBeShown:",
name: UIKeyboardWillShowNotification,
object: nil)
notificationCenter.addObserver(self,
selector: "keyboardWillBeHidden:",
name: UIKeyboardWillHideNotification,
object: nil)
}
// Called when the UIKeyboardDidShowNotification is sent.
func keyboardWillBeShown(sender: NSNotification) {
let info: NSDictionary = sender.userInfo!
let value: NSValue = info.valueForKey(UIKeyboardFrameBeginUserInfoKey) as! NSValue
let keyboardSize: CGSize = value.CGRectValue().size
let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height, 0.0)
mainScrollView.contentInset = contentInsets
mainScrollView.scrollIndicatorInsets = contentInsets
// If active text field is hidden by keyboard, scroll it so it's visible
// Your app might not need or want this behavior.
var aRect: CGRect = self.view.frame
aRect.size.height -= keyboardSize.height
}
// Called when the UIKeyboardWillHideNotification is sent
func keyboardWillBeHidden(sender: NSNotification) {
let contentInsets: UIEdgeInsets = UIEdgeInsetsZero
mainScrollView.contentInset = contentInsets
mainScrollView.scrollIndicatorInsets = contentInsets
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.registerForKeyboardNotifications()
}
override func viewDidDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// HIDE KEYBOARD ON TOUCH ****************************************
func hideKeyboard(){
widthField.resignFirstResponder()
heigthField.resignFirstResponder()
basecoatPriceField.resignFirstResponder()
topcoatPriceField.resignFirstResponder()
basecoatCanSizeField.resignFirstResponder()
topcoatCanSizeField.resignFirstResponder()
}
// *********************************************************************************
// ACTIONS
// *********************************************************************************
#IBAction func resetButton() {
resetInputAndLabels()
// resetDataModel()
}
// CHANGE UNIT **************************************************
#IBAction func unitSelectInput() {
switch unitSegmentController.selectedSegmentIndex {
case 0:
unitSetter = "metric"
resetInputAndLabels()
// resetDataModel()
//println("SWITCHED TO metric")
println(unitSegmentController.selectedSegmentIndex)
case 1:
unitSetter = "imperial"
resetInputAndLabels()
// resetDataModel()
//println("SWITCH TO imperial")
println(unitSegmentController.selectedSegmentIndex)
default:
println("Unit switch did not work")
}
}
// CHANGE COAT **********************************************
#IBAction func coatSelectInput() {
switch (self.unitSegmentController.selectedSegmentIndex) {
case 0:
coatSetter = 1
//println("SWITCHED TO coat 1")
println(unitSegmentController.selectedSegmentIndex)
case 1:
coatSetter = 2
//println("SWITCHED TO coat 2")
println(unitSegmentController.selectedSegmentIndex)
case 2:
coatSetter = 3
//println("SWITCHED TO coat 3")
println(unitSegmentController.selectedSegmentIndex)
default:
println("Coat switch did not work")
}
}
// GENERATE RESULTS **********************************************
#IBAction func generateResults() {
//SCROLL VIEW TO SHOW RESULTS - Only for 4s
let screenSize: CGRect = UIScreen.mainScreen().bounds
//println("Screen heigth - \(screenSize.height)")
if screenSize.height <= 480 {
UIScrollView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 1.5, initialSpringVelocity: 1.5, options: UIViewAnimationOptions.CurveLinear, animations: {
self.mainScrollView.contentOffset.y = 220.0
}, completion: {
Void in
UIView.animateWithDuration(0.6, delay: 0.0, usingSpringWithDamping: 0.1, initialSpringVelocity: 3.0, options: UIViewAnimationOptions.CurveLinear, animations: {}, completion: { Void in })
})
}
//SAVE TO COREDATA
//DETECT IF NO DATA HAS BEEN ENTERED
if widthField.text == "" || heigthField.text == "" || basecoatCanSizeField.text == "" || topcoatCanSizeField.text == "" {
alertViewLaunch(message: "I will need at least width, heigth, basecoat can size and topcoat can size to get the basic calculations done")
} else {
//STORE DATA DEPENDING ON UNIT
switch unitSetter {
case "metric": PaintEntity.createInManagedObjectContext(self.managedObjectContext!,
width: NSString(string: (widthField.text)).doubleValue,
heigth: NSString(string: (heigthField.text)).doubleValue,
basecoatPrice: NSString(string: (basecoatPriceField.text)).doubleValue,
basecoatCanSize: NSString(string: (basecoatCanSizeField.text)).doubleValue,
topcoatPrice: NSString(string: (topcoatPriceField.text)).doubleValue,
topcoatCanSize: NSString(string: (topcoatCanSizeField.text)).doubleValue,
unit: "metric",
coats: coatSetter)
case "imperial":PaintEntity.createInManagedObjectContext(self.managedObjectContext!,
width: NSString(string: (widthField.text)).doubleValue,
heigth: NSString(string: (heigthField.text)).doubleValue,
basecoatPrice: NSString(string: (basecoatPriceField.text)).doubleValue,
basecoatCanSize: NSString(string: (basecoatCanSizeField.text)).doubleValue,
topcoatPrice: NSString(string: (topcoatPriceField.text)).doubleValue,
topcoatCanSize: NSString(string: (topcoatCanSizeField.text)).doubleValue,
unit: "imperial",
coats: coatSetter)
default:
println("No unit detected")
}
printResults()
}
}
func printResults(){
let fetchRequest = NSFetchRequest(entityName: "PaintEntity")
let sortDescriptor = NSSortDescriptor(key: "date", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor]
fetchRequest.fetchLimit = 1
var error : NSError?
if let fetchResults = managedObjectContext!.executeFetchRequest(fetchRequest, error: &error) as? [PaintEntity] {
resultBasecoatAmount.text = "\(roundNumberToOne(fetchResults[0].resultBasecoatAmount.doubleValue))"
resultTopcoatAmount.text = "\(roundNumberToOne(fetchResults[0].resultTopcoatAmount.doubleValue))"
//println("I am fetching this \(fetchResults[0])")
if basecoatPriceField.text == "" || topcoatPriceField.text == "" {
resultBasecoatCost.textColor = UIColor(hue: 162/360.0, saturation: 65/100.0, brightness: 45/100.0, alpha: 100.0/100.0)
basecoatNoCostWarning.text = "Missing price"
resultBasecoatCost.text = "$0.00"
resultTopcoatCost.textColor = UIColor(hue: 162/360.0, saturation: 65/100.0, brightness: 45/100.0, alpha: 100.0/100.0)
topcoatNoCostWarning.text = "Missing price"
resultTopcoatCost.text = "$0.00"
}else{
if basecoatPriceField == "" {
resultBasecoatCost.textColor = UIColor(hue: 162/360.0, saturation: 65/100.0, brightness: 45/100.0, alpha: 100.0/100.0)
basecoatNoCostWarning.text = "Missing price"
resultBasecoatCost.text = "$0.00"
} else {
resultBasecoatCost.textColor = UIColor.whiteColor()
basecoatNoCostWarning.text = ""
resultBasecoatCost.text = "$\(roundNumberToTwo(fetchResults[0].resultBasecoatCost.doubleValue))"
}
if topcoatPriceField == "" {
resultTopcoatCost.textColor = UIColor(hue: 165/360.0, saturation: 63/100.0, brightness: 53/100.0, alpha: 100.0/100.0)
topcoatNoCostWarning.text = "Missing price"
resultTopcoatCost.text = "$0.00"
}else{
resultTopcoatCost.textColor = UIColor.whiteColor()
topcoatNoCostWarning.text = ""
resultTopcoatCost.text = "$\(roundNumberToTwo(fetchResults[0].resultTopcoatCost.doubleValue))"
}
}
}
}
}