Why can't the method be called? - ios

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.

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()
}
}

How does YouTube iOS app render the loading page?

Just want to confirm, is the following gray section from YouTube iOS app just placeholder image? I saw a few apps make like this, if not, how do they implement that?
use this if you want to achieve it without integrating a pods.
import UIKit
#objc public protocol ListLoadable
{
func ld_visibleContentViews()->[UIView]
}
#objc extension UITableView : ListLoadable
{
public func ld_visibleContentViews()->[UIView]
{
return (self.visibleCells as NSArray).value(forKey: "contentView") as!
[UIView]
}
}
#objc extension UIView
{
public func showShimmeryLoader(){
self.isUserInteractionEnabled = false
if self is UITableView{
ListLoader.addLoaderTo(self as! UITableView)
}else if self is UICollectionView{
ListLoader.addLoaderTo(self as! UICollectionView)
}else{
ListLoader.addLoaderToViews([self])
}
}
public func hideShimmeryLoader(){
self.isUserInteractionEnabled = true
if self is UITableView{
ListLoader.removeLoaderFrom(self as! UITableView)
}else if self is UICollectionView{
ListLoader.removeLoaderFrom(self as! UICollectionView)
}else{
ListLoader.removeLoaderFromViews([self])
}
}
}
#objc extension UICollectionView : ListLoadable
{
public func ld_visibleContentViews()->[UIView]
{
return (self.visibleCells as NSArray).value(forKey: "contentView") as!
[UIView]
}
}
#objc extension UIColor {
static func backgroundFadedGrey()->UIColor
{
return UIColor(red: (246.0/255.0), green: (247.0/255.0), blue:
(248.0/255.0), alpha: 1)
}
static func gradientFirstStop()->UIColor
{
return UIColor(red: (238.0/255.0), green: (238.0/255.0), blue:
(238.0/255.0), alpha: 1.0)
}
static func gradientSecondStop()->UIColor
{
return UIColor(red: (221.0/255.0), green: (221.0/255.0), blue:(221.0/255.0)
, alpha: 1.0);
}
}
#objc extension UIView{
func boundInside(_ superView: UIView){
self.translatesAutoresizingMaskIntoConstraints = false
superView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat:
"H:|-0-[subview]-0-|", options: NSLayoutConstraint.FormatOptions(),
metrics:nil, views:["subview":self]))
superView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat:
"V:|-0-[subview]-0-|", options: NSLayoutConstraint.FormatOptions(),
metrics:nil, views:["subview":self]))
}
}
extension CGFloat
{
func doubleValue()->Double
{
return Double(self)
}
}
#objc open class ListLoader: NSObject
{
static func addLoaderToViews(_ views : [UIView])
{
CATransaction.begin()
views.forEach { $0.ld_addLoader() }
CATransaction.commit()
}
static func removeLoaderFromViews(_ views: [UIView])
{
CATransaction.begin()
views.forEach { $0.ld_removeLoader() }
CATransaction.commit()
}
public static func addLoaderTo(_ list : ListLoadable )
{
self.addLoaderToViews(list.ld_visibleContentViews())
}
public static func removeLoaderFrom(_ list : ListLoadable )
{
self.removeLoaderFromViews(list.ld_visibleContentViews())
}
}
#objc class CutoutView : UIView
{
override func draw(_ rect: CGRect) {
super.draw(rect)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(UIColor.rgb(red: 231, green: 235, blue: 229, alpha:
1).cgColor)
context?.fill(self.bounds)
for view in (self.superview?.subviews)! {
if view != self {
context?.setBlendMode(.clear);
let rect = view.frame
let clipPath: CGPath = UIBezierPath(roundedRect: rect,
cornerRadius: view.layer.cornerRadius).cgPath
context?.addPath(clipPath)
context?.setFillColor(UIColor.clear.cgColor)
context?.closePath()
context?.fillPath()
}
}
}
override func layoutSubviews() {
self.setNeedsDisplay()
self.superview?.ld_getGradient()?.frame = (self.superview?.bounds)!
}
}
// TODO :- Allow caller to tweak these
var cutoutHandle: UInt8 = 0
var gradientHandle: UInt8 = 0
var loaderDuration = 0.85
var gradientWidth = 0.17
var gradientFirstStop = 0.1
#objc extension UIView
{
fileprivate func ld_getCutoutView()->UIView?
{
return objc_getAssociatedObject(self, &cutoutHandle) as! UIView?
}
fileprivate func ld_setCutoutView(_ aView : UIView)
{
return objc_setAssociatedObject(self, &cutoutHandle, aView,
.OBJC_ASSOCIATION_RETAIN)
}
fileprivate func ld_getGradient()->CAGradientLayer?
{
return objc_getAssociatedObject(self, &gradientHandle) as! CAGradientLayer?
}
fileprivate func ld_setGradient(_ aLayer : CAGradientLayer)
{
return objc_setAssociatedObject(self, &gradientHandle, aLayer,
.OBJC_ASSOCIATION_RETAIN)
}
fileprivate func ld_addLoader()
{
let gradient: CAGradientLayer = CAGradientLayer()
gradient.frame = CGRect(x: 0, y: 0, width: self.bounds.size.width , height:
self.bounds.size.height)
self.layer.insertSublayer(gradient, at:0)
self.configureAndAddAnimationToGradient(gradient)
self.addCutoutView()
}
fileprivate func ld_removeLoader()
{
self.ld_getCutoutView()?.removeFromSuperview()
self.ld_getGradient()?.removeAllAnimations()
self.ld_getGradient()?.removeFromSuperlayer()
for view in self.subviews {
view.alpha = 1
}
}
func configureAndAddAnimationToGradient(_ gradient : CAGradientLayer)
{
gradient.startPoint = CGPoint(x: -1.0 + CGFloat(gradientWidth), y: 0)
gradient.endPoint = CGPoint(x: 1.0 + CGFloat(gradientWidth), y: 0)
gradient.colors = [
UIColor.backgroundFadedGrey().cgColor,
UIColor.gradientFirstStop().cgColor,
UIColor.gradientSecondStop().cgColor,
UIColor.gradientFirstStop().cgColor,
UIColor.backgroundFadedGrey().cgColor
]
let startLocations = [NSNumber(value: gradient.startPoint.x.doubleValue()
as Double),NSNumber(value: gradient.startPoint.x.doubleValue() as
Double),NSNumber(value: 0 as Double),NSNumber(value: gradientWidth as
Double),NSNumber(value: 1 + gradientWidth as Double)]
gradient.locations = startLocations
let gradientAnimation = CABasicAnimation(keyPath: "locations")
gradientAnimation.fromValue = startLocations
gradientAnimation.toValue = [NSNumber(value: 0 as Double),NSNumber(value: 1
as Double),NSNumber(value: 1 as Double),NSNumber(value: 1 +
(gradientWidth - gradientFirstStop) as Double),NSNumber(value: 1 +
gradientWidth as Double)]
gradientAnimation.repeatCount = Float.infinity
gradientAnimation.fillMode = .forwards
gradientAnimation.isRemovedOnCompletion = false
gradientAnimation.duration = loaderDuration
gradient.add(gradientAnimation ,forKey:"locations")
self.ld_setGradient(gradient)
}
fileprivate func addCutoutView()
{
let cutout = CutoutView()
cutout.frame = self.bounds
cutout.backgroundColor = UIColor.clear
self.addSubview(cutout)
cutout.setNeedsDisplay()
cutout.boundInside(self)
for view in self.subviews {
if view != cutout {
view.alpha = 0
}
}
self.ld_setCutoutView(cutout)
}
}

Xcode 9.3.1 Unknown class in Interface Builder File

I have been trying to make an onboarding screen for my iOS game made using Sprite Kit. I am using the ramotion kit(https://github.com/Ramotion/paper-onboarding) for doing the same. I keep getting this error, Unknown class in interface builder and I have been stuck on this for ages. Here is my code for the GameViewController class:
import UIKit
import SpriteKit
import PaperOnboarding
protocol Controller {
func levelCompleted()
func levelFailed()
}
/* GameViewController is in charge of managing the game. This includes creating and
* changing levels, access to main menu, etc.
*/
var count = 0
class GameViewController: UIViewController, PaperOnboardingDataSource, PaperOnboardingDelegate
{
#IBOutlet var onboardingView: OnboardingView!
#IBOutlet var getStartedButton: UIButton!
#IBAction func playButtonPressed(_ sender: Any)
{
let controller = storyboard!.instantiateViewController(withIdentifier: "actualGame")
initialiseSKScene()
}
var currentLevel: Level? = nil
var config: GameConfiguration?
var skView: SKView?
override func viewDidLoad()
{
super.viewDidLoad()
onboardingView.dataSource = self
onboardingView.delegate = self
}
func initialiseSKScene()
{
let skView = initialiseSKView()
do
{
config = try GameConfiguration(file: "level_json_sample", size: skView.bounds.size)
}
catch let error
{
print("Level cannot be loaded!")
print(error)
}
let teethArray = config!.getTeethByLevel(id: 1)
let objectArray = config!.getObjectsByLevel(id: 1)
print(objectArray[0])
// Use the JSON file to open level 1
currentLevel = Level(size: skView.bounds.size, bgFile: "background2.png",
teethArray: teethArray, otherArray: objectArray, c: self as! Controller)
currentLevel?.scaleMode = SKSceneScaleMode.resizeFill
skView.presentScene(currentLevel)
}
func onboardingItemsCount() -> Int
{
return 3
}
func onboardingItem(at index: Int) -> OnboardingItemInfo
{
let onBoardItem1 = OnboardingItemInfo(informationImage: UIImage(named: "rocket")!,
title: "A Great Rocket Start",
description: "Caramels cheesecake bonbon bonbon topping. Candy halvah cotton candy chocolate bar cake. Fruitcake liquorice candy canes marshmallow topping powder.",
pageIcon: UIImage(named: "rocket")!,
color: UIColor(red: 217/255, green: 72/255, blue: 89/255, alpha: 1),
titleColor: UIColor.white,
descriptionColor: UIColor.white,
titleFont: UIFont(name: "AvenirNext-Bold", size: 24)!,
descriptionFont: UIFont(name: "AvenirNext-Regular", size: 18)!)
let onBoardItem2 = OnboardingItemInfo(informationImage: UIImage(named: "brush")!,
title: "Design your Experience",
description: "Caramels cheesecake bonbon bonbon topping. Candy halvah cotton candy chocolate bar cake. Fruitcake liquorice candy canes marshmallow topping powder.",
pageIcon: UIImage(named: "brush")!,
color: UIColor(red: 106/255, green: 166/255, blue: 211/255, alpha: 1),
titleColor: UIColor.white,
descriptionColor: UIColor.white,
titleFont: UIFont(name: "AvenirNext-Bold", size: 24)!,
descriptionFont: UIFont(name: "AvenirNext-Regular", size: 18)!)
let onBoardItem3 = OnboardingItemInfo(informationImage: UIImage(named: "notification")!,
title: "Stay Up To Date",
description: "Get notified of important updates.",
pageIcon: UIImage(named: "notification")!,
color: UIColor(red: 168/255, green: 200/255, blue: 78/255, alpha: 1),
titleColor: UIColor.white,
descriptionColor: UIColor.white,
titleFont: UIFont(name: "AvenirNext-Bold", size: 24)!,
descriptionFont: UIFont(name: "AvenirNext-Regular", size: 18)!)
return [onBoardItem1,onBoardItem2,onBoardItem3][index]
}
/* Initialises the SKView where we display the game */
private func initialiseSKView() -> SKView
{
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsPhysics = true
skView.showsNodeCount = true
skView.ignoresSiblingOrder = true
skView.isMultipleTouchEnabled = false
return skView
}
/* This method is called by the currentLevel when it is completed */
func levelCompleted() {
// check if there exists a higher level than currentLevel.id
// change to next level or present winning screen
let reveal = SKTransition.flipHorizontal(withDuration: 0.5)
let gameOverScene = GameOverScene(size: skView!.bounds.size, won: false)
skView?.presentScene(gameOverScene, transition: reveal)
}
func onboardingConfigurationItem(_: OnboardingContentViewItem, index _: Int)
{
}
func onboardingWillTransitonToIndex(_ index: Int)
{
if index == 1
{
if self.getStartedButton.alpha == 1
{
UIView.animate(withDuration: 0.2, animations:
{
self.getStartedButton.alpha = 0
})
}
}
}
func onboardingDidTransitonToIndex(_ index: Int)
{
if index == 2
{
UIView.animate(withDuration: 0.4, animations:
{
self.getStartedButton.alpha = 1
})
}
}
/* This method is called by the currentLevel when it is failed */
func levelFailed() {
// present losing screen
let reveal = SKTransition.flipHorizontal(withDuration: 0.5)
let gameOverScene = GameOverScene(size: skView!.bounds.size, won: false)
skView?.presentScene(gameOverScene, transition: reveal)
}
}
I get the Unknown class in interface builder error and this line in ViewDidLoad() shows:
"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"
onboardingView.dataSource = self
I have checked all my outlets and classes in interface builder as well and all of them are proper!
Would really appreciate any help!

Why are UIColor.white, red, green, and blue not working, but all other color constants are working just fine?

I've just started migrating some Swift code over to Swift 3. The formatting for color constants has changed from
let color = UIColor.yellowColor() // Swift 2
let color = UIColor.yellow // Swift 3
Most of my project's code has been migrating over just fine using this new syntax. However, some of the UIColor color constants are not working: UIColor.white, UIColor.red, UIColor.green, and UIColor.blue. All other UIColor constants, like UIColor.yellow, work just fine. The malfunctioning constants show up in autocomplete, and websites online report that they work (http://leaks.wanari.com/2016/09/26/converting-project-swift-3-0/).
However, when I compile the following file:
import SpriteKit
let aColor = UIColor.black
let aColor2 = UIColor.darkGray
let aColor3 = UIColor.lightGray
let aColor4 = UIColor.white
let aColor5 = UIColor.gray
let aColor6 = UIColor.red
let aColor7 = UIColor.green
let aColor8 = UIColor.blue
let aColor9 = UIColor.cyan
let aColor10 = UIColor.yellow
let aColor11 = UIColor.magenta
let aColor12 = UIColor.orange
let aColor13 = UIColor.purple
let aColor14 = UIColor.brown
let aColor15 = UIColor.clear
let aFakeColor = UIColor.fakeColor
It gives the following errors:
Instance member 'white' cannot be used on type 'UIColor'
Instance member 'red' cannot be used on type 'UIColor'
Instance member 'green' cannot be used on type 'UIColor'
Instance member 'blue' cannot be used on type 'UIColor'
Type 'UIColor' has no member 'fakeColor'
Now the last error makes perfect sense; there is no color constant called fakeColor. But this shows that the compiler is seeing the malfunctioning color constants, as it's giving a different error.
According to Apple's documentation, the malfunctioning color constants do exist. Why can't my compiler see them?
Update: I found the issue.
I had an extension to UIColor that made it act more Swifty. It allowed accessing the RGB components as shown below. Now that UIColor has red, green, and blue properties that represent the colors red, green, and blue, there was a conflict.
For anyone else that's having a similar issue: make sure to check if you have any extensions that be causing the problem.
Swift 2 Extension
//
// UIColor+Swifty.swift
//
// Created by Cin316 on 3/6/16.
// Usage is permitted under the MIT license.
// This does not work in Swift 3.0 !
//
import SpriteKit
public extension UIColor {
public var alpha: CGFloat? {
get {
var a: CGFloat = 0
if (self.getWhite(nil, alpha: &a)) {
return a
} else {
return nil
}
}
}
public var white: CGFloat? {
get {
var w: CGFloat = 0
if (self.getWhite(&w, alpha: nil)) {
return w
} else {
return nil
}
}
}
public var red: CGFloat? {
get {
var r: CGFloat = 0
if (self.getRed(&r, green: nil, blue: nil, alpha: nil)) {
return r
} else {
return nil
}
}
}
public var green: CGFloat? {
get {
var g: CGFloat = 0
if (self.getRed(nil, green: &g, blue: nil, alpha: nil)) {
return g
} else {
return nil
}
}
}
public var blue: CGFloat? {
get {
var b: CGFloat = 0
if (self.getRed(nil, green: nil, blue: &b, alpha: nil)) {
return b
} else {
return nil
}
}
}
public var hue: CGFloat? {
get {
var h: CGFloat = 0
if (self.getHue(&h, saturation: nil, brightness: nil, alpha: nil)) {
return h
} else {
return nil
}
}
}
public var saturation: CGFloat? {
get {
var s: CGFloat = 0
if (self.getHue(nil, saturation: &s, brightness: nil, alpha: nil)) {
return s
} else {
return nil
}
}
}
public var brightness: CGFloat? {
get {
var b: CGFloat = 0
if (self.getHue(nil, saturation: nil, brightness: &b, alpha: nil)) {
return b
} else {
return nil
}
}
}
}
Swift 3 Extension
//
// UIColor+Swifty.swift
//
// Created by Cin316 on 3/6/16.
// Usage is permitted under the MIT license.
// Notice the addition of "Comp" to conflicting properties.
//
import SpriteKit
public extension UIColor {
public var alphaComp: CGFloat? {
get {
var a: CGFloat = 0
if (self.getWhite(nil, alpha: &a)) {
return a
} else {
return nil
}
}
}
public var whiteComp: CGFloat? {
get {
var w: CGFloat = 0
if (self.getWhite(&w, alpha: nil)) {
return w
} else {
return nil
}
}
}
public var redComp: CGFloat? {
get {
var r: CGFloat = 0
if (self.getRed(&r, green: nil, blue: nil, alpha: nil)) {
return r
} else {
return nil
}
}
}
public var greenComp: CGFloat? {
get {
var g: CGFloat = 0
if (self.getRed(nil, green: &g, blue: nil, alpha: nil)) {
return g
} else {
return nil
}
}
}
public var blueComp: CGFloat? {
get {
var b: CGFloat = 0
if (self.getRed(nil, green: nil, blue: &b, alpha: nil)) {
return b
} else {
return nil
}
}
}
public var hue: CGFloat? {
get {
var h: CGFloat = 0
if (self.getHue(&h, saturation: nil, brightness: nil, alpha: nil)) {
return h
} else {
return nil
}
}
}
public var saturation: CGFloat? {
get {
var s: CGFloat = 0
if (self.getHue(nil, saturation: &s, brightness: nil, alpha: nil)) {
return s
} else {
return nil
}
}
}
public var brightness: CGFloat? {
get {
var b: CGFloat = 0
if (self.getHue(nil, saturation: nil, brightness: &b, alpha: nil)) {
return b
} else {
return nil
}
}
}
}

Swift BAD ACCESS Code = 2

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.

Resources