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

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

Related

How to make an animation shadowOffset in Swift?

I wrote the code but I can not understand why it does not work...
func animate(vc: UIView) {
vc.layer.shadowColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
vc.layer.shadowRadius = 5
vc.layer.shadowOffset = CGSize(width: 0, height: 0)
let animationX = CABasicAnimation()
animationX.keyPath = "shadowOffset"
animationX.fromValue = vc.layer.shadowOffset
animationX.toValue = CGSize(width: 10, height: 10)
animationX.duration = 1
vc.layer.add(animationX, forKey: animationX.keyPath)
}
#IBAction func buttonTapped(_ sender: UIButton) {
animate(vc: sender)
}
Does anyone know how this works?
Couple of things missing
shadowPath
shadowOpacity
vc.layer.masksToBounds = false
vc.layer.shadowColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
vc.layer.shadowRadius = 5
vc.layer.shadowOffset = CGSize(width: 0, height: 0)
vc.layer.shadowPath = UIBezierPath(rect: vc.bounds).cgPath
vc.layer.shadowOpacity = 1.0
let animationX = CABasicAnimation()
animationX.keyPath = "shadowOffset"
animationX.fromValue = vc.layer.shadowOffset
animationX.toValue = CGSize(width: 10, height: 10)
animationX.duration = 1
vc.layer.add(animationX, forKey: animationX.keyPath)
By default shadowOpacity is 0.
Final O/P
EDIT:
If you want shadow to persist in its position even after animation specify
fillMode
isRemovedOnCompletion
final code will look like
func animate(vc: UIView) {
vc.layer.masksToBounds = false
vc.layer.shadowColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
vc.layer.shadowRadius = 5
vc.layer.shadowOffset = CGSize(width: 0, height: 0)
vc.layer.shadowPath = UIBezierPath(rect: vc.bounds).cgPath
vc.layer.shadowOpacity = 1.0
let animationX = CABasicAnimation()
animationX.keyPath = "shadowOffset"
animationX.fromValue = vc.layer.shadowOffset
animationX.toValue = CGSize(width: 10, height: 10)
animationX.duration = 1
animationX.fillMode = .forwards
animationX.isRemovedOnCompletion = false
vc.layer.add(animationX, forKey: animationX.keyPath)
}
Final O/P looks like:

Swift - Working With Gradients

I have encountered a problem involving setting gradients for labels and buttons. I know this question has been asked a lot, but no answer has seemed to solve my problem. Here is the screen as I want it to look:
This is my code:
#IBOutlet weak var loginButton: UIButton!
#IBOutlet weak var signUpButton: UIButton!
#IBOutlet weak var logoLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
loginButton.backgroundColor = UIColor.clear
let loginButtonGradient = createBlueGreenGradient(from: loginButton.bounds)
self.view.layer.insertSublayer(loginButtonGradient, at: 0)
signUpButton.backgroundColor = UIColor.clear
let signUpButtonGradient = createBlueGreenGradient(from: signUpButton.bounds)
self.view.layer.insertSublayer(signUpButtonGradient, at: 0)
logoLabel.backgroundColor = UIColor.clear
let logoLabelGradient = createBlueGreenGradient(from: logoLabel.bounds)
self.view.layer.insertSublayer(logoLabelGradient, at: 0)
loginButton.layer.cornerRadius = 100
signUpButton.layer.cornerRadius = 100
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func createBlueGreenGradient(from bounds: CGRect) -> CAGradientLayer{
let topColor = UIColor(red: 84/255, green: 183/255, blue: 211/255, alpha: 1)
let bottomColor = UIColor(red: 119/255, green: 202/255, blue: 151/255, alpha: 1)
let gradientColors: [UIColor] = [topColor, bottomColor]
let gradientLocations: [NSNumber] = [0.0, 1.0]
let gradientLayer = CAGradientLayer()
gradientLayer.colors = gradientColors
gradientLayer.locations = gradientLocations
gradientLayer.frame = bounds
return gradientLayer
}
And this is the wrong result:
Somebody please help me. I'm not sure what I'm doing wrong.
There are lots of issue with your code.
Divide the color with Float number instead of Int means it should be 255.0 not 255.
Now for colors property of CAGradientLayer you need to set array of CGColor not array of UIColor.
Also set startPoint and endPoint property of CAGradientLayer to make horizontal gradient color.
Currently you are adding this GradientLayer in your self.view instead of its specific button.
Set the cornerRadius of your button on basis of its height not with some constant 100 also after setting cornerRadius you need to also set masksToBounds property of layer to true.
Now for your logo label, you cannot set textColor as Gradient color directly what you need to do is draw the desired gradient on a UIImage and then use that UIImage to set the color pattern for your Label check this SO reference for that.
After making all this changes your code should be like.
func createBlueGreenGradient(from bounds: CGRect) -> CAGradientLayer{
let topColor = UIColor(red: 84/255.0, green: 183/255.0, blue: 211/255.0, alpha: 1).cgColor
let bottomColor = UIColor(red: 119/255.0, green: 202/255.0, blue: 151/255.0, alpha: 1).cgColor
let gradientColors = [topColor, bottomColor]
let gradientLocations: [NSNumber] = [0.0, 1.0]
let gradientLayer = CAGradientLayer()
gradientLayer.colors = gradientColors
gradientLayer.locations = gradientLocations
//Set startPoint and endPoint property also
gradientLayer.startPoint = CGPoint(x: 0, y: 0)
gradientLayer.endPoint = CGPoint(x: 1, y: 0)
gradientLayer.frame = bounds
return gradientLayer
}
Now set gradientLayer in viewDidLoad this way.
override func viewDidLoad() {
super.viewDidLoad()
let loginButtonGradient = createBlueGreenGradient(from: loginButton.bounds)
self.loginButton.layer.insertSublayer(loginButtonGradient, at: 0)
let signUpButtonGradient = createBlueGreenGradient(from: signUpButton.bounds)
self.signUpButton.layer.insertSublayer(signUpButtonGradient, at: 0)
loginButton.layer.cornerRadius = loginButton.frame.size.height / 2
loginButton.layer.masksToBounds = true
signUpButton.layer.cornerRadius = signUpButton.frame.size.height / 2
signUpButton.layer.masksToBounds = true
}
Your method like this:
func createBlueGreenGradient(from bounds: CGRect) -> CAGradientLayer{
let topColor = UIColor(red: 84/255, green: 183/255, blue: 211/255, alpha: 1).cgColor
let bottomColor = UIColor(red: 119/255, green: 202/255, blue: 151/255, alpha: 1).cgColor
let gradientColors = [topColor, bottomColor]
let gradientLocations: [NSNumber] = [0.0, 1.0]
let gradientLayer = CAGradientLayer()
gradientLayer.colors = gradientColors
gradientLayer.locations = gradientLocations
gradientLayer.frame = bounds
return gradientLayer
}
Oh my goodness I had the same problem, but played around with it. This is caused because you didnt add .cgcolor. For example :
let topColor = UIColor(red: 84/255, green: 183/255, blue: 211/255, alpha: 1).cgColor
let bottomColor = UIColor(red: 119/255, green: 202/255, blue: 151/255, alpha: 1).cgColor
let gradientColors = [topColor, bottomColor]
Let me know if it works.

Swift 2.1 - How do I change the uidatepicker so it only allows for time instead of date?

The following code below allows for the user to select a date, however I want to change that to 'Time' via AM/PM, so the user can only select a set time instead it being a date. I want this separate and not combined, I appreciate if someone could help me here thanks.
import Foundation
import UIKit
import QuartzCore
class DatePickerDialog: UIView {
typealias DatePickerCallback = (date: NSDate) -> Void
/* Consts */
private let kDatePickerDialogDefaultButtonHeight: CGFloat = 50
private let kDatePickerDialogDefaultButtonSpacerHeight: CGFloat = 1
private let kDatePickerDialogCornerRadius: CGFloat = 7
private let kDatePickerDialogDoneButtonTag: Int = 1
/* Views */
private var dialogView: UIView!
private var titleLabel: UILabel!
private var datePicker: UIDatePicker!
private var cancelButton: UIButton!
private var doneButton: UIButton!
/* Vars */
private var defaultDate: NSDate?
private var datePickerMode: UIDatePickerMode?
private var callback: DatePickerCallback?
/* Overrides */
init() {
super.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height))
setupView()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func setupView() {
self.dialogView = createContainerView()
self.dialogView!.layer.shouldRasterize = true
self.dialogView!.layer.rasterizationScale = UIScreen.mainScreen().scale
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.mainScreen().scale
self.dialogView!.layer.opacity = 0.5
self.dialogView!.layer.transform = CATransform3DMakeScale(1.3, 1.3, 1)
self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)
self.addSubview(self.dialogView!)
UIApplication.sharedApplication().windows.first!.addSubview(self)
}
/* Handle device orientation changes */
func deviceOrientationDidChange(notification: NSNotification) {
/* TODO */
}
/* Create the dialog view, and animate opening the dialog */
func show(title: String, datePickerMode: UIDatePickerMode = .Date, callback: DatePickerCallback) {
show(title, doneButtonTitle: "Done", cancelButtonTitle: "Cancel", datePickerMode: datePickerMode, callback: callback)
}
func show(title: String, doneButtonTitle: String, cancelButtonTitle: String, defaultDate: NSDate = NSDate(), datePickerMode: UIDatePickerMode = .Date, callback: DatePickerCallback) {
self.titleLabel.text = title
self.doneButton.setTitle(doneButtonTitle, forState: .Normal)
self.cancelButton.setTitle(cancelButtonTitle, forState: .Normal)
self.datePickerMode = datePickerMode
self.callback = callback
self.defaultDate = defaultDate
self.datePicker.datePickerMode = self.datePickerMode ?? .Date
self.datePicker.date = self.defaultDate ?? NSDate()
/* Anim */
UIView.animateWithDuration(
0.2,
delay: 0,
options: UIViewAnimationOptions.CurveEaseInOut,
animations: { () -> Void in
self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4)
self.dialogView!.layer.opacity = 1
self.dialogView!.layer.transform = CATransform3DMakeScale(1, 1, 1)
},
completion: nil
)
}
/* Dialog close animation then cleaning and removing the view from the parent */
private func close() {
let currentTransform = self.dialogView.layer.transform
let startRotation = (self.valueForKeyPath("layer.transform.rotation.z") as? NSNumber) as? Double ?? 0.0
let rotation = CATransform3DMakeRotation((CGFloat)(-startRotation + M_PI * 270 / 180), 0, 0, 0)
self.dialogView.layer.transform = CATransform3DConcat(rotation, CATransform3DMakeScale(1, 1, 1))
self.dialogView.layer.opacity = 1
UIView.animateWithDuration(
0.2,
delay: 0,
options: UIViewAnimationOptions.TransitionNone,
animations: { () -> Void in
self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)
self.dialogView.layer.transform = CATransform3DConcat(currentTransform, CATransform3DMakeScale(0.6, 0.6, 1))
self.dialogView.layer.opacity = 0
}) { (finished: Bool) -> Void in
for v in self.subviews {
v.removeFromSuperview()
}
self.removeFromSuperview()
}
}
/* Creates the container view here: create the dialog, then add the custom content and buttons */
private func createContainerView() -> UIView {
let screenSize = countScreenSize()
let dialogSize = CGSizeMake(
300,
230
+ kDatePickerDialogDefaultButtonHeight
+ kDatePickerDialogDefaultButtonSpacerHeight)
// For the black background
self.frame = CGRectMake(0, 0, screenSize.width, screenSize.height)
// This is the dialog's container; we attach the custom content and the buttons to this one
let dialogContainer = UIView(frame: CGRectMake((screenSize.width - dialogSize.width) / 2, (screenSize.height - dialogSize.height) / 2, dialogSize.width, dialogSize.height))
// First, we style the dialog to match the iOS8 UIAlertView >>>
let gradient: CAGradientLayer = CAGradientLayer(layer: self.layer)
gradient.frame = dialogContainer.bounds
gradient.colors = [UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1).CGColor,
UIColor(red: 233/255, green: 233/255, blue: 233/255, alpha: 1).CGColor,
UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1).CGColor]
let cornerRadius = kDatePickerDialogCornerRadius
gradient.cornerRadius = cornerRadius
dialogContainer.layer.insertSublayer(gradient, atIndex: 0)
dialogContainer.layer.cornerRadius = cornerRadius
dialogContainer.layer.borderColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1).CGColor
dialogContainer.layer.borderWidth = 1
dialogContainer.layer.shadowRadius = cornerRadius + 5
dialogContainer.layer.shadowOpacity = 0.1
dialogContainer.layer.shadowOffset = CGSizeMake(0 - (cornerRadius + 5) / 2, 0 - (cornerRadius + 5) / 2)
dialogContainer.layer.shadowColor = UIColor.blackColor().CGColor
dialogContainer.layer.shadowPath = UIBezierPath(roundedRect: dialogContainer.bounds, cornerRadius: dialogContainer.layer.cornerRadius).CGPath
// There is a line above the button
let lineView = UIView(frame: CGRectMake(0, dialogContainer.bounds.size.height - kDatePickerDialogDefaultButtonHeight - kDatePickerDialogDefaultButtonSpacerHeight, dialogContainer.bounds.size.width, kDatePickerDialogDefaultButtonSpacerHeight))
lineView.backgroundColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1)
dialogContainer.addSubview(lineView)
// ˆˆˆ
//Title
self.titleLabel = UILabel(frame: CGRectMake(10, 10, 280, 30))
self.titleLabel.textAlignment = NSTextAlignment.Center
self.titleLabel.font = UIFont.boldSystemFontOfSize(17)
dialogContainer.addSubview(self.titleLabel)
self.datePicker = UIDatePicker(frame: CGRectMake(0, 30, 0, 0))
self.datePicker.autoresizingMask = UIViewAutoresizing.FlexibleRightMargin
self.datePicker.frame.size.width = 300
dialogContainer.addSubview(self.datePicker)
// Add the buttons
addButtonsToView(dialogContainer)
return dialogContainer
}
/* Add buttons to container */
private func addButtonsToView(container: UIView) {
let buttonWidth = container.bounds.size.width / 2
self.cancelButton = UIButton(type: UIButtonType.Custom) as UIButton
self.cancelButton.frame = CGRectMake(
0,
container.bounds.size.height - kDatePickerDialogDefaultButtonHeight,
buttonWidth,
kDatePickerDialogDefaultButtonHeight
)
self.cancelButton.setTitleColor(UIColor(red: 0, green: 0.5, blue: 1, alpha: 1), forState: UIControlState.Normal)
self.cancelButton.setTitleColor(UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5), forState: UIControlState.Highlighted)
self.cancelButton.titleLabel!.font = UIFont.boldSystemFontOfSize(14)
self.cancelButton.layer.cornerRadius = kDatePickerDialogCornerRadius
container.addSubview(self.cancelButton)
self.doneButton = UIButton(type: UIButtonType.Custom) as UIButton
self.doneButton.frame = CGRectMake(
buttonWidth,
container.bounds.size.height - kDatePickerDialogDefaultButtonHeight,
buttonWidth,
kDatePickerDialogDefaultButtonHeight
)
self.doneButton.tag = kDatePickerDialogDoneButtonTag
self.doneButton.setTitleColor(UIColor(red: 0, green: 0.5, blue: 1, alpha: 1), forState: UIControlState.Normal)
self.doneButton.setTitleColor(UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5), forState: UIControlState.Highlighted)
self.doneButton.titleLabel!.font = UIFont.boldSystemFontOfSize(14)
self.doneButton.layer.cornerRadius = kDatePickerDialogCornerRadius
self.doneButton.addTarget(self, action: "buttonTapped:", forControlEvents: UIControlEvents.TouchUpInside)
container.addSubview(self.doneButton)
}
func buttonTapped(sender: UIButton!) {
if sender.tag == kDatePickerDialogDoneButtonTag {
self.callback?(date: self.datePicker.date)
}
close()
}
/* Helper function: count and return the screen's size */
func countScreenSize() -> CGSize {
let screenWidth = UIScreen.mainScreen().bounds.size.width
let screenHeight = UIScreen.mainScreen().bounds.size.height
return CGSizeMake(screenWidth, screenHeight)
}
}
Here is the action in a separate view controller.
#IBAction func datePickerTapped(sender: AnyObject) {
DatePickerDialog().show("Select Date of Incident", doneButtonTitle: "Done", cancelButtonTitle: "Cancel", datePickerMode: .Date) {
(date) -> Void in
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy" //format style. you can change according to yours
let dateString = dateFormatter.stringFromDate(date)
self.textField3.text = dateString
}
}
If by "separately," you mean prompting for the date and then prompting for the time, you can simply call the show method again and pass in the appropriate UIDatePickerMode (.Time in this case) and format your time according to your requirements.
Like so:
DatePickerDialog().show("Select Time of Incident", doneButtonTitle: "Done", cancelButtonTitle: "Cancel", datePickerMode: .Time) {
//format your time accordingly
//self.textField3.text = timeString
}

How to remove the time from Date Picker?

What I want to achieve here is to remove the "TIME" from the UITextfield once I have selected a date. For example "D/M/Y" I want this only to display and not the time "00:00:00" or "+0000".
This piece of code does not require the element of "UIDate Picker" to be selected as I already know how to disable the time this way through the attributes inspector but not this way.
I think it needs to be done programmatically.
Code in the separate class:
import Foundation
import UIKit
import QuartzCore
class DatePickerDialog: UIView {
typealias DatePickerCallback = (date: NSDate) -> Void
/* Consts */
private let kDatePickerDialogDefaultButtonHeight: CGFloat = 50
private let kDatePickerDialogDefaultButtonSpacerHeight: CGFloat = 1
private let kDatePickerDialogCornerRadius: CGFloat = 7
private let kDatePickerDialogDoneButtonTag: Int = 1
/* Views */
private var dialogView: UIView!
private var titleLabel: UILabel!
private var datePicker: UIDatePicker!
private var cancelButton: UIButton!
private var doneButton: UIButton!
/* Vars */
private var defaultDate: NSDate?
private var datePickerMode: UIDatePickerMode?
private var callback: DatePickerCallback?
/* Overrides */
init() {
super.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height))
setupView()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func setupView() {
self.dialogView = createContainerView()
self.dialogView!.layer.shouldRasterize = true
self.dialogView!.layer.rasterizationScale = UIScreen.mainScreen().scale
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.mainScreen().scale
self.dialogView!.layer.opacity = 0.5
self.dialogView!.layer.transform = CATransform3DMakeScale(1.3, 1.3, 1)
self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)
self.addSubview(self.dialogView!)
UIApplication.sharedApplication().windows.first!.addSubview(self)
}
/* Handle device orientation changes */
func deviceOrientationDidChange(notification: NSNotification) {
/* TODO */
}
/* Create the dialog view, and animate opening the dialog */
func show(title: String, datePickerMode: UIDatePickerMode = .Date, callback: DatePickerCallback) {
show(title, doneButtonTitle: "Done", cancelButtonTitle: "Cancel", datePickerMode: datePickerMode, callback: callback)
}
func show(title: String, doneButtonTitle: String, cancelButtonTitle: String, defaultDate: NSDate = NSDate(), datePickerMode: UIDatePickerMode = .Date, callback: DatePickerCallback) {
self.titleLabel.text = title
self.doneButton.setTitle(doneButtonTitle, forState: .Normal)
self.cancelButton.setTitle(cancelButtonTitle, forState: .Normal)
self.datePickerMode = datePickerMode
self.callback = callback
self.defaultDate = defaultDate
self.datePicker.datePickerMode = self.datePickerMode ?? .Date
self.datePicker.date = self.defaultDate ?? NSDate()
/* Anim */
UIView.animateWithDuration(
0.2,
delay: 0,
options: UIViewAnimationOptions.CurveEaseInOut,
animations: { () -> Void in
self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4)
self.dialogView!.layer.opacity = 1
self.dialogView!.layer.transform = CATransform3DMakeScale(1, 1, 1)
},
completion: nil
)
}
/* Dialog close animation then cleaning and removing the view from the parent */
private func close() {
let currentTransform = self.dialogView.layer.transform
let startRotation = (self.valueForKeyPath("layer.transform.rotation.z") as? NSNumber) as? Double ?? 0.0
let rotation = CATransform3DMakeRotation((CGFloat)(-startRotation + M_PI * 270 / 180), 0, 0, 0)
self.dialogView.layer.transform = CATransform3DConcat(rotation, CATransform3DMakeScale(1, 1, 1))
self.dialogView.layer.opacity = 1
UIView.animateWithDuration(
0.2,
delay: 0,
options: UIViewAnimationOptions.TransitionNone,
animations: { () -> Void in
self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)
self.dialogView.layer.transform = CATransform3DConcat(currentTransform, CATransform3DMakeScale(0.6, 0.6, 1))
self.dialogView.layer.opacity = 0
}) { (finished: Bool) -> Void in
for v in self.subviews {
v.removeFromSuperview()
}
self.removeFromSuperview()
}
}
/* Creates the container view here: create the dialog, then add the custom content and buttons */
private func createContainerView() -> UIView {
let screenSize = countScreenSize()
let dialogSize = CGSizeMake(
300,
230
+ kDatePickerDialogDefaultButtonHeight
+ kDatePickerDialogDefaultButtonSpacerHeight)
// For the black background
self.frame = CGRectMake(0, 0, screenSize.width, screenSize.height)
// This is the dialog's container; we attach the custom content and the buttons to this one
let dialogContainer = UIView(frame: CGRectMake((screenSize.width - dialogSize.width) / 2, (screenSize.height - dialogSize.height) / 2, dialogSize.width, dialogSize.height))
// First, we style the dialog to match the iOS8 UIAlertView >>>
let gradient: CAGradientLayer = CAGradientLayer(layer: self.layer)
gradient.frame = dialogContainer.bounds
gradient.colors = [UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1).CGColor,
UIColor(red: 233/255, green: 233/255, blue: 233/255, alpha: 1).CGColor,
UIColor(red: 218/255, green: 218/255, blue: 218/255, alpha: 1).CGColor]
let cornerRadius = kDatePickerDialogCornerRadius
gradient.cornerRadius = cornerRadius
dialogContainer.layer.insertSublayer(gradient, atIndex: 0)
dialogContainer.layer.cornerRadius = cornerRadius
dialogContainer.layer.borderColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1).CGColor
dialogContainer.layer.borderWidth = 1
dialogContainer.layer.shadowRadius = cornerRadius + 5
dialogContainer.layer.shadowOpacity = 0.1
dialogContainer.layer.shadowOffset = CGSizeMake(0 - (cornerRadius + 5) / 2, 0 - (cornerRadius + 5) / 2)
dialogContainer.layer.shadowColor = UIColor.blackColor().CGColor
dialogContainer.layer.shadowPath = UIBezierPath(roundedRect: dialogContainer.bounds, cornerRadius: dialogContainer.layer.cornerRadius).CGPath
// There is a line above the button
let lineView = UIView(frame: CGRectMake(0, dialogContainer.bounds.size.height - kDatePickerDialogDefaultButtonHeight - kDatePickerDialogDefaultButtonSpacerHeight, dialogContainer.bounds.size.width, kDatePickerDialogDefaultButtonSpacerHeight))
lineView.backgroundColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1)
dialogContainer.addSubview(lineView)
// ˆˆˆ
//Title
self.titleLabel = UILabel(frame: CGRectMake(10, 10, 280, 30))
self.titleLabel.textAlignment = NSTextAlignment.Center
self.titleLabel.font = UIFont.boldSystemFontOfSize(17)
dialogContainer.addSubview(self.titleLabel)
self.datePicker = UIDatePicker(frame: CGRectMake(0, 30, 0, 0))
self.datePicker.autoresizingMask = UIViewAutoresizing.FlexibleRightMargin
self.datePicker.frame.size.width = 300
dialogContainer.addSubview(self.datePicker)
// Add the buttons
addButtonsToView(dialogContainer)
return dialogContainer
}
/* Add buttons to container */
private func addButtonsToView(container: UIView) {
let buttonWidth = container.bounds.size.width / 2
self.cancelButton = UIButton(type: UIButtonType.Custom) as UIButton
self.cancelButton.frame = CGRectMake(
0,
container.bounds.size.height - kDatePickerDialogDefaultButtonHeight,
buttonWidth,
kDatePickerDialogDefaultButtonHeight
)
self.cancelButton.setTitleColor(UIColor(red: 0, green: 0.5, blue: 1, alpha: 1), forState: UIControlState.Normal)
self.cancelButton.setTitleColor(UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5), forState: UIControlState.Highlighted)
self.cancelButton.titleLabel!.font = UIFont.boldSystemFontOfSize(14)
self.cancelButton.layer.cornerRadius = kDatePickerDialogCornerRadius
container.addSubview(self.cancelButton)
self.doneButton = UIButton(type: UIButtonType.Custom) as UIButton
self.doneButton.frame = CGRectMake(
buttonWidth,
container.bounds.size.height - kDatePickerDialogDefaultButtonHeight,
buttonWidth,
kDatePickerDialogDefaultButtonHeight
)
self.doneButton.tag = kDatePickerDialogDoneButtonTag
self.doneButton.setTitleColor(UIColor(red: 0, green: 0.5, blue: 1, alpha: 1), forState: UIControlState.Normal)
self.doneButton.setTitleColor(UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5), forState: UIControlState.Highlighted)
self.doneButton.titleLabel!.font = UIFont.boldSystemFontOfSize(14)
self.doneButton.layer.cornerRadius = kDatePickerDialogCornerRadius
self.doneButton.addTarget(self, action: "buttonTapped:", forControlEvents: UIControlEvents.TouchUpInside)
container.addSubview(self.doneButton)
}
func buttonTapped(sender: UIButton!) {
if sender.tag == kDatePickerDialogDoneButtonTag {
self.callback?(date: self.datePicker.date)
}
close()
}
/* Helper function: count and return the screen's size */
func countScreenSize() -> CGSize {
let screenWidth = UIScreen.mainScreen().bounds.size.width
let screenHeight = UIScreen.mainScreen().bounds.size.height
return CGSizeMake(screenWidth, screenHeight)
}
}
Code here defined in Viewcontroller.swift:
#IBAction func datePickerTapped(sender: AnyObject) {
DatePickerDialog().show("Select Date of Incident", doneButtonTitle: "Done", cancelButtonTitle: "Cancel", datePickerMode: .Date) {
(date) -> Void in
self.textField3.text = "\(date)"
}
}
Its simple
change this line to
self.textField3.text = "\(date)"
to
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd" //format style. you can change according to yours
var dateString = dateFormatter.stringFromDate(date)
self.textField3.text = dateString

Convert bar chart to a grouped bar chart with danielgindi/ios-charts and Swift

i have created the simple bar chart with the library at https://github.com/danielgindi/ios-charts still can't figure out how to make this a grouped bar chart. I've added the units sold array to the chart, but don't know how to get the unitBought array to the chart to make it a grouped chart.please help.
#IBOutlet weak var barChartView: BarChartView!
override func viewDidLoad() {
super.viewDidLoad()
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
let unitsSold = [20.0, 4.0, 6.0, 3.0, 12.0, 16.0, 4.0, 18.0, 2.0, 4.0, 5.0, 12.8]
let unitsBought = [20.0, 4.0, 6.0, 3.0, 12.0, 16.0, 4.0, 18.0, 2.0, 4.0, 5.0, 12.8]
setChart(months, values: unitsSold)
}
//functions
func setChart(dataPoints: [String], values: [Double]) {
barChartView.noDataText = "You need to provide data for the chart."
var dataEntries: [BarChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = BarChartDataEntry(value: values[i], xIndex: i)
dataEntries.append(dataEntry)
}
let chartDataSet = BarChartDataSet(yVals: dataEntries, label: "Units Sold")
let chartData = BarChartData(xVals: months, dataSet: chartDataSet)
barChartView.data = chartData
barChartView.backgroundColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1)
barChartView.gridBackgroundColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1)
barChartView.legend.enabled = false
barChartView.leftAxis.drawGridLinesEnabled = false
barChartView.leftAxis.drawAxisLineEnabled = true
barChartView.rightAxis.drawGridLinesEnabled = false
barChartView.rightAxis.drawAxisLineEnabled = false
barChartView.rightAxis.drawLabelsEnabled = false
barChartView.xAxis.drawGridLinesEnabled = false
barChartView.xAxis.drawLabelsEnabled = true
}
let months = ["Jan", "Feb", "Mar", "Apr", "May"]
let unitsSold = [20.0, 4.0, 6.0, 3.0, 12.0]
let unitsBought = [10.0, 14.0, 60.0, 13.0, 2.0]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
barChartView.delegate = self
barChartView.noDataText = "You need to provide data for the chart."
barChartView.chartDescription?.text = "sales vs bought "
//legend
let legend = barChartView.legend
legend.enabled = true
legend.horizontalAlignment = .right
legend.verticalAlignment = .top
legend.orientation = .vertical
legend.drawInside = true
legend.yOffset = 10.0;
legend.xOffset = 10.0;
legend.yEntrySpace = 0.0;
let xaxis = barChartView.xAxis
xaxis.valueFormatter = axisFormatDelegate
xaxis.drawGridLinesEnabled = true
xaxis.labelPosition = .bottom
xaxis.centerAxisLabelsEnabled = true
xaxis.valueFormatter = IndexAxisValueFormatter(values:self.months)
xaxis.granularity = 1
let leftAxisFormatter = NumberFormatter()
leftAxisFormatter.maximumFractionDigits = 1
let yaxis = barChartView.leftAxis
yaxis.spaceTop = 0.35
yaxis.axisMinimum = 0
yaxis.drawGridLinesEnabled = false
barChartView.rightAxis.enabled = false
//axisFormatDelegate = self
setChart()
}
func setChart() {
barChartView.noDataText = "You need to provide data for the chart."
var dataEntries: [BarChartDataEntry] = []
var dataEntries1: [BarChartDataEntry] = []
for i in 0..<self.months.count {
let dataEntry = BarChartDataEntry(x: Double(i) , y: self.unitsSold[i])
dataEntries.append(dataEntry)
let dataEntry1 = BarChartDataEntry(x: Double(i) , y: self.self.unitsBought[i])
dataEntries1.append(dataEntry1)
//stack barchart
//let dataEntry = BarChartDataEntry(x: Double(i), yValues: [self.unitsSold[i],self.unitsBought[i]], label: "groupChart")
}
let chartDataSet = BarChartDataSet(values: dataEntries, label: "Unit sold")
let chartDataSet1 = BarChartDataSet(values: dataEntries1, label: "Unit Bought")
let dataSets: [BarChartDataSet] = [chartDataSet,chartDataSet1]
chartDataSet.colors = [UIColor(red: 230/255, green: 126/255, blue: 34/255, alpha: 1)]
//chartDataSet.colors = ChartColorTemplates.colorful()
//let chartData = BarChartData(dataSet: chartDataSet)
let chartData = BarChartData(dataSets: dataSets)
let groupSpace = 0.3
let barSpace = 0.05
let barWidth = 0.3
// (0.3 + 0.05) * 2 + 0.3 = 1.00 -> interval per "group"
let groupCount = self.months.count
let startYear = 0
chartData.barWidth = barWidth;
barChartView.xAxis.axisMinimum = Double(startYear)
let gg = chartData.groupWidth(groupSpace: groupSpace, barSpace: barSpace)
print("Groupspace: \(gg)")
barChartView.xAxis.axisMaximum = Double(startYear) + gg * Double(groupCount)
chartData.groupBars(fromX: Double(startYear), groupSpace: groupSpace, barSpace: barSpace)
//chartData.groupWidth(groupSpace: groupSpace, barSpace: barSpace)
barChartView.notifyDataSetChanged()
barChartView.data = chartData
//background color
barChartView.backgroundColor = UIColor(red: 189/255, green: 195/255, blue: 199/255, alpha: 1)
//chart animation
barChartView.animate(xAxisDuration: 1.5, yAxisDuration: 1.5, easingOption: .linear)
}
You haven't actually done anything with unitsBought.
For a bar chart you can do two things:
Add another DataSet with your unitsBought
Use the other overload of BarCharDataEntry(values: [Double], xIndex: Int) or BarCharDataEntry(values: [Double], xIndex: Int, label: String) to pass multiple values per entry, which makes it stacked.
func setChartBarGroupDataSet(dataPoints: [String], values: [Double], values2: [Double],sortIndex:Int) {
var dataEntries: [BarChartDataEntry] = []
var dataEntries2: [BarChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = BarChartDataEntry(value: values[i], xIndex: i)
dataEntries.append(dataEntry)
}
for i in 0..<dataPoints.count {
let dataEntry = BarChartDataEntry(value: values2[i], xIndex: i)
dataEntries2.append(dataEntry)
}
let chartDataSet = BarChartDataSet(yVals: dataEntries, label: " ")
let chartDataSet2 = BarChartDataSet(yVals: dataEntries2, label: " ")
chartDataSet2.colors = [UIColor(red: 255/255, green: 70/255, blue: 108/255, alpha: 1)]
chartDataSet.colors = [UIColor(red: 49/255, green: 27/255, blue: 146/255, alpha: 1)]
let dataSets: [BarChartDataSet] = [chartDataSet,chartDataSet2]
let data = BarChartData(xVals: dataPoints, dataSets: dataSets)
barChartView.data = data
barChartView.descriptionText = ""
barChartView.rightAxis.drawGridLinesEnabled = false
barChartView.rightAxis.drawAxisLineEnabled = false
barChartView.rightAxis.drawLabelsEnabled = false
barChartView.animate(xAxisDuration: 2.0, yAxisDuration: 2.0, easingOption: .EaseInBounce)
}