Swift BAD ACCESS Code = 2 - ios

I'm trying to create an app that displays headlines from the NY Times politics section on 2/3 of a view on an AppleTV and shows a line chart above a pie chart on the other 1/3 of the view. I've written two separate programs, one that shows the headlines and one that shows the charts, but when trying to combine them I'm running into this error of
"BAD ACCESS"
at the line.
pieChartView!.holeColor = UIColor(hue: 0.0111, saturation: 0.15, brightness: 1, alpha: 1.0)
pieChartView!.descriptionText = ""
Any insight would be appreciated, thanks!
import UIKit
import Charts
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var table: UITableView!
#IBOutlet weak var pieChartView: PieChartView?
#IBOutlet weak var lineChartView: LineChartView?
let baseURL = "http://api.nytimes.com/svc/topstories/v1/politics.json?api-key=dd56f74b26c444f497b4588fd2944146"
var headlines = [String]()
var bernieSanders = [String]()
var hillaryClinton = [String]()
var donaldTrump = [String]()
var bernieCount: Double = 0.0
var hillaryCount: Double = 0.0
var donaldCount: Double = 0.0
var headlineCount = [Double]()
override func viewDidLoad() {
super.viewDidLoad()
let candidates = ["Sanders", "Clinton", "Trump"]
self.getJSON()
sleep(2)
setChart(candidates, values: headlineCount)
sleep(2)
self.table.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getJSON() {
let url = NSURL(string: baseURL)
let request = NSURLRequest(URL: url!)
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let task = session.dataTaskWithRequest(request){ (data, response, error) -> Void in
if error == nil {
let SwiftyJSON = JSON(data: data!)
let theTitle = SwiftyJSON["results"].arrayValue
for title in theTitle {
let titles = title["title"].stringValue
self.headlines.append(titles)
}
for headline in self.headlines {
if headline.lowercaseString.rangeOfString("sanders") != nil {
self.bernieSanders.append(headline)
}
if headline.lowercaseString.rangeOfString("clinton") != nil {
self.hillaryClinton.append(headline)
}
if headline.lowercaseString.rangeOfString("trump") != nil {
self.donaldTrump.append(headline)
}
}
self.bernieCount = Double(self.bernieSanders.count)
self.hillaryCount = Double(self.hillaryClinton.count)
self.donaldCount = Double(self.donaldTrump.count)
self.headlineCount.append(self.bernieCount)
self.headlineCount.append(self.hillaryCount)
self.headlineCount.append(self.donaldCount)
print("Number Of Headlines That Mention Each Candidate")
print("Bernie: \(self.bernieCount)")
print("Hillary: \(self.hillaryCount)")
print("Donald: \(self.donaldCount)\n")
print(self.headlines)
}
else {
print("there was an error")
}
}
task.resume()
}
// From the UITAbleViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return headlines.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.table.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
cell.textLabel!.text = self.headlines[indexPath.row]
cell.textLabel!.font = UIFont(name:"Avenir", size:25)
return cell
}
// From the UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("You tapped on cell # \(indexPath.row)")
}
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: "")
let pieChartData = PieChartData(xVals: dataPoints, dataSet: pieChartDataSet)
pieChartView!.backgroundColor = UIColor(hue: 0.0111, saturation: 0.15, brightness: 1, alpha: 1.0)
pieChartView!.holeColor = UIColor(hue: 0.0111, saturation: 0.15, brightness: 1, alpha: 1.0)
pieChartView!.descriptionText = ""
pieChartView!.data = pieChartData
let blue = UIColor(hue: 0.6194, saturation: 1, brightness: 0.89, alpha: 1.0)
let lightblue = UIColor(hue: 0.5222, saturation: 1, brightness: 0.92, alpha: 1.0)
let red = UIColor(hue: 0, saturation: 1, brightness: 0.86, alpha: 1.0)
let colors: [UIColor] = [blue, lightblue, red]
// for _ 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)
// }
//
pieChartDataSet.colors = colors
let lineChartDataSet = LineChartDataSet(yVals: dataEntries, label: "NY Times Headlines")
let lineChartData = LineChartData(xVals: dataPoints, dataSet: lineChartDataSet)
lineChartDataSet.colors = [NSUIColor(hue: 0.3194, saturation: 1, brightness: 0.66, alpha: 1.0)]
lineChartDataSet.circleColors = [NSUIColor(hue: 0.3194, saturation: 1, brightness: 0.66, alpha: 1.0)]
lineChartView!.backgroundColor = UIColor(hue: 0.0111, saturation: 0.15, brightness: 1, alpha: 1.0)
lineChartView!.descriptionText = ""
lineChartView!.xAxis.labelPosition = .Bottom
lineChartView!.data = lineChartData
}
}

as #vadian suggested, I needed to set the class of the custom view accordingly.

For people who may also strand in this cryptic error: My Problem was that I changed the class of an outlet, but forgot to change it in the Storyboard-View. After the correct declaration of view and outlet, the error was gone.

Related

How to animate GMSMarker?

How i can perform animation like this in GMSMarker?
I tried to add layer to GMSMarker layer but it doesn't work..
let pulse = Pulsing(center: CGPoint(x: 240, y: 480),radius: 36, fillColor: #colorLiteral(red: 0.9979501367, green: 0.7617542744, blue: 0.05507106334, alpha: 0.5), strokeColor: #colorLiteral(red: 0.9979501367, green: 0.7617542744, blue: 0.05507106334, alpha: 1), lineWidth: 1)
pulse.animationDuration = 0.8
fromLoctionMarker.layer.addSublayer(pulse)
I just created five circles
and lunch timer for every circle and animate circle border circle opacity color and circle radius changing smoothly using timer
use recursive to make the animation infinity
// marker animation variables
private var numberOfCircels = 0
private var circlesTimers = [Timer]()
private var circlesRadius = [Int]()
private var circlesColors = [CGFloat]()
private var circlesBorderColors = [CGFloat]()
private var gmsCircles = [[GMSCircle]]()
private func createCircel(){
if numberOfCircels == 5 { return }
let tempNumberOfCircels = numberOfCircels
let circleTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(timerFiredForCircel), userInfo: ["currentIndex": tempNumberOfCircels], repeats: true)
circlesTimers.append(circleTimer)
circlesRadius.append(0)
gmsCircles.append([GMSCircle]())
circlesColors.append(0.2)
circlesBorderColors.append(0.7)
numberOfCircels = numberOfCircels + 1
print(numberOfCircels, "numberOfCircels")
}
#objc
private func timerFiredForCircel(timer: Timer){
guard let context = timer.userInfo as? [String: Int] else { return }
guard let currentIndex = context["currentIndex"] else { return }
let location = order.fromLocation.location
let circel = GMSCircle(position: location, radius: CLLocationDistance(circlesRadius[currentIndex]))
circel.fillColor = #colorLiteral(red: 1, green: 0.7607843137, blue: 0.05882352941, alpha: 1).withAlphaComponent(circlesColors[currentIndex])
circel.strokeColor = #colorLiteral(red: 1, green: 0.7607843137, blue: 0.05882352941, alpha: 1).withAlphaComponent(circlesBorderColors[currentIndex])
circel.strokeWidth = 1
gmsCircles[currentIndex].append(circel)
if circlesRadius[currentIndex] < 150{
circlesRadius[currentIndex] += 3
circlesColors[currentIndex] -= (0.2 / 50)
circlesBorderColors[currentIndex] -= 0.014
}else if circlesRadius[currentIndex] >= 150{
circlesRadius[currentIndex] = 0
circlesColors[currentIndex] = 0.2
circlesBorderColors[currentIndex] = 0.7
}
circel.map = googleMab
for i in 0..<gmsCircles[currentIndex].count - 1{
let circle = gmsCircles[currentIndex][i]
circle.map = nil
gmsCircles[currentIndex].removeAll(where: { $0 == circle})
}
if circlesRadius[currentIndex] == 30{
self.createCircel()
}
}

Why can't the method be called?

I just cloned a project from GitHub, and I added the relevant folder to my project. When I run my project, the animation effect can be displayed normally, but the images on the animation can't be displayed. I have tried re-cloning the complete code, but it still does the same. I'm sure that all the codes and images are completely cloned.
I added a breakpoint, realizing that the func circleMenu is never called.
Can someone please explain this, or at least tell me what I need to write to get it correct?
Here is my code:
import UIKit
import CircleMenu
extension UIColor {
static func color(_ red: Int, green: Int, blue: Int, alpha: Float) -> UIColor {
return UIColor(
red: 1.0 / 255.0 * CGFloat(red),
green: 1.0 / 255.0 * CGFloat(green),
blue: 1.0 / 255.0 * CGFloat(blue),
alpha: CGFloat(alpha))
}
}
class FirstViewController: UIViewController, CircleMenuDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate{
#IBAction func to2(_ sender: UIButton) {
let sb = UIStoryboard(name:"Main",bundle: Bundle.main)
let view2 = sb.instantiateViewController(withIdentifier: "view2")
layerTransition(animTye: .cube, subType: .ramdom, curve: .EaseInEaseOut, duration: 0.4, layer: (self.view.window?.layer)!)
self.present(view2,animated: true,completion: nil)
}
// let secondView = ViewController()
#IBAction func toView2(_ sender: UIButton) {
let sb = UIStoryboard(name:"Main",bundle: Bundle.main)
let secondViewController = sb.instantiateViewController(withIdentifier: "SecondViewController")
layerTransition(animTye: .cube, subType: .ramdom, curve: .EaseInEaseOut, duration: 0.4, layer: (self.view.window?.layer)!)
self.present(secondViewController,animated: true,completion: nil)
}
var imagePickerController:UIImagePickerController!
enum TransitionAnimType : Int {
case fade = 0,
push,
reveal,
moveIn,
cube,
suckEffect,
oglFlip,
rippleEffect,
pageCurl,
pageUnCurl,
cameraIrisHollowOpen,
cameraIrisHollowClose,
curlDown,
curlUp,
flipFromLeft,
flipFromRight,
ramdom
}
enum TransitionSubType : Int {
case top = 0,
left,
bottom,
right,
ramdom
}
enum TransitionCurve : Int {
case Default = 0,
EaseIn,
EaseOut,
EaseInEaseOut,
Linear,
Ramdom
}
private func animationType(animType: TransitionAnimType) -> String {
let animTypeArray = ["fade", "push", "reveal", "moveIn", "cube", "suckEffect", "oglFlip", "rippleEffect", "pageCurl", "pageUnCurl", "cameraIrisHollowOpen", "cameraIrisHollowClose", "curlDown", "curlUp", "flipFromLeft", "flipFromRight", "ramdom"]
return objectFromDataSource(array: animTypeArray, index: animType.rawValue, isRamdom: (TransitionAnimType.ramdom == animType)) as! String
}
private func animationSubType(subType: TransitionSubType) -> String {
let animSubTypeArray = [CATransitionSubtype.fromTop, CATransitionSubtype.fromLeft, CATransitionSubtype.fromBottom, CATransitionSubtype.fromRight]
return objectFromDataSource(array: animSubTypeArray, index: subType.rawValue, isRamdom: (TransitionSubType.ramdom == subType)) as! String
}
private func animationCurve(curve: TransitionCurve) -> String {
let animCurveArray = [CAMediaTimingFunctionName.default, CAMediaTimingFunctionName.easeIn, CAMediaTimingFunctionName.easeOut, CAMediaTimingFunctionName.easeInEaseOut, CAMediaTimingFunctionName.linear]
return objectFromDataSource(array: animCurveArray, index: curve.rawValue, isRamdom: (TransitionCurve.Ramdom == curve)) as! String
}
private func objectFromDataSource(array: Array<Any>, index: Int, isRamdom: Bool) -> AnyObject {
let count = array.count
let i = isRamdom ? Int(arc4random_uniform(UInt32(count))) : index
return array[i] as AnyObject
}
func layerTransition(animTye: TransitionAnimType, subType: TransitionSubType, curve: TransitionCurve, duration: CGFloat, layer: CALayer) {
let key = "transition"
if layer.animation(forKey: key) != nil {
layer.removeAnimation(forKey: key)
}
let transition = CATransition()
transition.duration = CFTimeInterval(duration)
transition.type = CATransitionType(rawValue: animationType(animType: animTye))
transition.subtype = CATransitionSubtype(rawValue: animationSubType(subType: subType))
transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName(rawValue: animationCurve(curve: curve)))
transition.isRemovedOnCompletion = true
layer.add(transition, forKey: key)
}
// let colors = [UIColor.redColor(), UIColor.grayColor(), UIColor.greenColor(), UIColor.purpleColor()]
let items: [(icon: String, color: UIColor)] = [
("icon_home", UIColor(red: 0.19, green: 0.57, blue: 1, alpha: 1)),
("icon_search", UIColor(red: 0.22, green: 0.74, blue: 0, alpha: 1)),
("notifications-btn", UIColor(red: 0.96, green: 0.23, blue: 0.21, alpha: 1)),
("settings-btn", UIColor(red: 0.51, green: 0.15, blue: 1, alpha: 1)),
("nearby-btn", UIColor(red: 1, green: 0.39, blue: 0, alpha: 1))
]
// #IBInspectable var buttonsCount: Int = 3
// #IBInspectable var duration: Double = 2 // circle animation duration
// #IBInspectable var distance: Float = 100 // distance between center button and buttons
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
}
// MARK: <CircleMenuDelegate>
func circleMenu(_: CircleMenu, willDisplay button: UIButton, atIndex: Int) {
button.backgroundColor = items[atIndex].color
button.setImage(UIImage(named: items[atIndex].icon), for: .normal)
let image = UIImage(named:items[atIndex].icon)
// set highlited image
let highlightedImage = UIImage(named: items[atIndex].icon)?.withRenderingMode(.alwaysTemplate)
button.setImage(highlightedImage, for: .highlighted)
button.tintColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3)
}
func circleMenu(_: CircleMenu, buttonWillSelected _: UIButton, atIndex: Int) {
print("button will selected: \(atIndex)")
}
func circleMenu(_: CircleMenu, buttonDidSelected _: UIButton, atIndex: Int) {
// let sb = UIStoryboard(name:"Main",bundle: Bundle.main)
// let secondView = sb.instantiateViewController(withIdentifier: "secondView")
print("button did selected: \(atIndex)")
if(atIndex == 0)
{
if(UIImagePickerController.isSourceTypeAvailable(.camera))
{
self.imagePickerController = UIImagePickerController()
self.imagePickerController.delegate = self
self.imagePickerController.allowsEditing = true
self.imagePickerController.sourceType = UIImagePickerController.SourceType.camera
layerTransition(animTye: .cameraIrisHollowOpen, subType: .ramdom, curve: .EaseInEaseOut, duration: 0.4, layer: (self.view.window?.layer)!)
self.present(self.imagePickerController,animated: true,completion: nil)
}
}
}
}
At this moment you only declare your delegate. Make sure you also set the delegate otherwise your delegate methodes wouldn't be called.

Correct data not showing in ios Charts

Im using Charts Version 3.0.1. Im currently teaching myself Swift by converting my Rails project. I have no knowledge of Objective C so please bear with me; I've done ok so far.
My code below is/may not be formatted correctly as Im missing the days array in the PieChart:
Numbers seem not to be correct. The code:
#IBOutlet weak var chartView: PieChartView!
override func viewDidLoad() {
super.viewDidLoad()
let days = ["Mo", "Tu", "Wed", "Thur", "Fri", "Sat", "Sun"]
let gross = [11.00, 90.95, 250.00, 40.90, 60.88, 99.99, 25.00]
setChart(dataPoints: days, values: gross)
}
func setChart(dataPoints: [String], values: [Double]) {
var dataEntries: [ChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = ChartDataEntry(x: values[i], y: Double(i))
dataEntries.append(dataEntry)
}
let pieChartDataSet = PieChartDataSet(values: dataEntries, label: "Gross Income")
pieChartDataSet.sliceSpace = 2.0
let pieChartData = PieChartData(dataSets: [pieChartDataSet]) // somewhere here confuses me.
var colors: [UIColor] = []
for _ 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)
}
pieChartDataSet.colors = colors
chartView.data = pieChartData
}
Have I missed out something? Your second eye would be highly appreciated.
You have changed x & y values and hence index is coming as your pie chart's value. Also, please use PieChartDataEntry.
(working code on my box)
override func viewDidLoad() {
super.viewDidLoad()
let days = ["Mo", "Tu", "Wed", "Thur", "Fri", "Sat", "Sun"]
let gross = [11.00, 90.95, 250.00, 40.90, 60.88, 99.99, 25.00]
setChart(days: days, gross: gross)
}
func setChart(days: [String], gross: [Double]) {
var dataEntries: [ChartDataEntry] = []
for i in 0..<days.count {
let dataEntry = PieChartDataEntry(value : gross[i], label : days[i])
dataEntries.append(dataEntry)
}
let pieChartDataSet = PieChartDataSet(values: dataEntries, label: "Gross Income")
pieChartDataSet.sliceSpace = 2.0
let pieChartData = PieChartData(dataSets: [pieChartDataSet])
var colors: [UIColor] = []
for _ in 0..<days.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)
}
pieChartDataSet.colors = colors
pieChartView.data = pieChartData
}
Try this and let me know.

Pie chart using Charts library with swift

I am integrating pie chart in my app using Charts library and getting issue with chart data my code is
import UIKit
import Charts
class ViewController: UIViewController {
#IBOutlet weak var pieChartView: PieChartView!
override func viewDidLoad() {
super.viewDidLoad()
let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
let unitsSold = [10.0, 4.0, 6.0, 3.0, 12.0, 16.0]
setChart(dataPoints: months, values: unitsSold)
}
func setChart(dataPoints: [String], values: [Double]) {
var dataEntries: [ChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry1 = ChartDataEntry(x: Double(i), y: values[i], data: dataPoints[i] as AnyObject)
dataEntries.append(dataEntry1)
}
print(dataEntries[0].data)
let pieChartDataSet = PieChartDataSet(values: dataEntries, label: "Units Sold")
let pieChartData = PieChartData(dataSet: pieChartDataSet)
pieChartView.data = pieChartData
var colors: [UIColor] = []
for _ 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)
}
pieChartDataSet.colors = colors
}
}
and when run app I getting something this
but I need pie chart in full data records like in below screen shot
Update for this question.
func updateChartData() {
let chart = PieChartView(frame: self.view.frame)
// 2. generate chart data entries
let track = ["Income", "Expense", "Wallet", "Bank"]
let money = [650, 456.13, 78.67, 856.52]
var entries = [PieChartDataEntry]()
for (index, value) in money.enumerated() {
let entry = PieChartDataEntry()
entry.y = value
entry.label = track[index]
entries.append( entry)
}
// 3. chart setup
let set = PieChartDataSet( values: entries, label: "Pie Chart")
// this is custom extension method. Download the code for more details.
var colors: [UIColor] = []
for _ in 0..<money.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)
}
set.colors = colors
let data = PieChartData(dataSet: set)
chart.data = data
chart.noDataText = "No data available"
// user interaction
chart.isUserInteractionEnabled = true
let d = Description()
d.text = "iOSCharts.io"
chart.chartDescription = d
chart.centerText = "Pie Chart"
chart.holeRadiusPercent = 0.2
chart.transparentCircleColor = UIColor.clear
self.view.addSubview(chart)
}
The reason all the information isn't showing up is because you are using a parent initialiser when creating the entry point.
Instead of
let dataEntry1 = ChartDataEntry(x: Double(i), y: values[i], data: dataPoints[i] as AnyObject)
try this instead
let dataEntry1 = PieChartDataEntry(value: Double(i), label: dataPoints[i], data: dataPoints[i] as AnyObject)
The PieChartDataEntry is specifically for Pie charts so you should see the month show up in the chart.
Hopefully this gets you on the right track

Found nil while unwrapping an Optional value, Error

I don't know where that optional is. please help! I really need this, I haven't used optional values in my code.
import UIKit
class ViewController: UIViewController {
//this is the outlet for the sliders RGB values
#IBOutlet weak var redSlider: UISlider!
#IBOutlet weak var greenSlider: UISlider!
#IBOutlet weak var blueSlider: UISlider!
//this are the outlets for the labels
#IBOutlet weak var redLabelValue: UILabel!
#IBOutlet weak var greenLabelValue: UILabel!
#IBOutlet weak var blueLabelValue: UILabel!
#IBOutlet weak var hexColor: UILabel!
func changeThumbImage() {
let redThumbImage = UIImage(named: "RedThumb#3x")
redSlider.setThumbImage(redThumbImage, forState: .Normal)
let greenThumbImage = UIImage(named: "GreenThumb#3x")
greenSlider.setThumbImage(greenThumbImage, forState: .Normal)
let blueThumbImage = UIImage(named: "BlueThumb#3x")
blueSlider.setThumbImage(blueThumbImage, forState: .Normal)
}
func colorValues() {
var roundedRed = UInt32(redSlider.value)
var roundedGreen = UInt32(greenSlider.value)
var roundedBlue = Int32(blueSlider.value)
//converts the slider value to a string
redLabelValue.text = String(stringInterpolationSegment: roundedRed)
greenLabelValue.text = String(stringInterpolationSegment: roundedGreen)
blueLabelValue.text = String(stringInterpolationSegment: roundedBlue)
}
func rgbValues() {
var redValue = Int(redSlider.value)
var greenValue = Int(greenSlider.value)
var blueValue = Int(blueSlider.value)
}
//VIEW DID LOAD
override func viewDidLoad() {
super.viewDidLoad()
updateBackgroundColor()
colorValues()
changeThumbImage()
redSlider = UISlider(frame: CGRect(x: 100,y: 100,width: 200,height: 25))
func getRandomColor() -> UIColor{
let uniformRed = UInt32(redSlider.value)
let uniformGreen = UInt32(greenSlider.value)
let uniformBlue = UInt32(blueSlider.value)
var randomRed:CGFloat = CGFloat(arc4random_uniform(uniformRed))
var randomGreen:CGFloat = CGFloat(arc4random_uniform(uniformGreen))
var randomBlue:CGFloat = CGFloat(arc4random_uniform(uniformBlue))
return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0)
}
//view.backgroundColor = getRandomColor()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func updateBackgroundColor() {
colorValues()
//constant to set the value of the slider to a CGFloat
let redValue = CGFloat(redSlider.value/255)
let greenValue = CGFloat(greenSlider.value/255)
let blueValue = CGFloat(blueSlider.value/255)
//set the RGBA values
view.backgroundColor = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1)
//get the hexadecimal value from the RGB color values
let hexValue = String(format:"%02X", Int(redSlider.value)) + String(format:"%02X", Int(greenSlider.value)) + String(format:"%02X", Int(blueSlider.value))
hexColor.text = "#\(hexValue)"
}
//get rid of status bar
override func prefersStatusBarHidden() -> Bool {
return true
}
}
Well, first off, all of your outlets could potentially be nil at some point, so a good start would be adding ? to optionally unwrap them all. If you do this, it will just do nothing instead of crash in the case that the Optional is nil. Below I went through and added this to some of your code, but you may need to add a few more ? to other optionals I overlooked. Another way to do this is to use if-let unwrapping, which will reduce the amount of "?", but increase the amount of nesting.
func changeThumbImage() {
let redThumbImage = UIImage(named: "RedThumb#3x")
redSlider?.setThumbImage(redThumbImage, forState: .Normal)
let greenThumbImage = UIImage(named: "GreenThumb#3x")
greenSlider?.setThumbImage(greenThumbImage, forState: .Normal)
let blueThumbImage = UIImage(named: "BlueThumb#3x")
blueSlider?.setThumbImage(blueThumbImage, forState: .Normal)
}
////
func colorValues() {
var roundedRed = UInt32(redSlider.value)
var roundedGreen = UInt32(greenSlider.value)
var roundedBlue = Int32(blueSlider.value)
//converts the slider value to a string
redLabelValue?.text = String(stringInterpolationSegment: roundedRed)
greenLabelValue?.text = String(stringInterpolationSegment: roundedGreen)
blueLabelValue?.text = String(stringInterpolationSegment: roundedBlue)
}
Also use if-let here to safely unwrap the sliders...
#IBAction func updateBackgroundColor() {
colorValues()
if let red = redSlider, green = greenSlider, blue = blueSlider{
let redValue = CGFloat(red.value/255)
let greenValue = CGFloat(green.value/255)
let blueValue = CGFloat(blue.value/255)
//set the RGBA values
view.backgroundColor = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1)
//get the hexadecimal value from the RGB color values
let hexValue = String(format:"%02X", Int(redSlider.value)) + String(format:"%02X", Int(greenSlider.value)) + String(format:"%02X", Int(blueSlider.value))
hexColor?.text = "#\(hexValue)"
}
}

Resources