How to make a combined chart of "line chart" and "bar chart"? - swift3

i found methods for swift2 but couldn't make a swift3 one. Can anybody help me making swift3 code of these combined chart?
I found these codes:
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
unitsSold = [20.0, 4.0, 6.0,20.0, 4.0, 6.0,20.0, 4.0, 6.0,20.0, 4.0, 6.0]
databozi = [10.0, 11.0, 12.0,10.0, 11.0, 12.0,10.0, 11.0, 12.0,10.0, 11.0, 12.0]
func convertCombines(dataEntryX forX:[String],dataEntryY forY: [Double], dataEntryZ forZ: [Double]) {
var dataEntries = [BarChartDataEntry]()
var dataEntrieszor = [ChartDataEntry]()
for i in 0..<forX.count {
dataEntries.append(BarChartDataEntry(x: forZ[i], y: Double(i)))
dataEntrieszor.append(ChartDataEntry(x: forY[i], y: Double(i)))
}
let lineChartSet = LineChartDataSet(values: dataEntrieszor, label: "Line Data")
let lineChartData = LineChartData(dataSets: [lineChartSet])
let barChartSet = BarChartDataSet(values: dataEntries, label: "Bar Data")
let barChartData = BarChartData(dataSets: [barChartSet])
//ui
lineChartSet.setColor(UIColor.red)
lineChartSet.setCircleColor(UIColor.red)
let comData = CombinedChartData(dataSets: [lineChartSet,barChartSet])
comData.barData = barChartData
comData.lineData = lineChartData
combinedChartViewOut.data = comData
combinedChartViewOut.notifyDataSetChanged()
}
my Example code pic
my Example code pic
but
need code like :
Example Combined pic

fix code :
func convertCombines(dataEntryX forX:[String],dataEntryY forY: [Double], dataEntryZ forZ: [Double]) {
var dataEntries: [BarChartDataEntry] = []
var dataEntrieszor: [ChartDataEntry] = [ChartDataEntry]()
for (i, v) in forY.enumerated() {
let dataEntry = ChartDataEntry(x: Double(i), y: v, data: forX as AnyObject?)
dataEntrieszor.append(dataEntry)
}
for (i, v) in forZ.enumerated() {
let dataEntry = BarChartDataEntry(x: Double(i), y: v, data: forX as AnyObject?)
dataEntries.append(dataEntry)
}
let lineChartSet = LineChartDataSet(values: dataEntrieszor, label: "Line Data")
let lineChartData = LineChartData(dataSets: [lineChartSet])
let barChartSet = BarChartDataSet(values: dataEntries, label: "Bar Data")
let barChartData = BarChartData(dataSets: [barChartSet])
//ui
lineChartSet.setColor(UIColor.red)
lineChartSet.setCircleColor(UIColor.red)
let comData = CombinedChartData(dataSets: [lineChartSet,barChartSet])
comData.barData = barChartData
comData.lineData = lineChartData
combinedChartViewOut.data = comData
combinedChartViewOut.notifyDataSetChanged()
combinedChartViewOut.xAxis.valueFormatter = IndexAxisValueFormatter(values:months)
combinedChartViewOut.xAxis.granularity = 1
combinedChartViewOut.animate(xAxisDuration: 2.0, yAxisDuration: 2.0, easingOption: .easeInCirc)
}

Related

.removeAll() no longer working on devices running iOS 16+

I have the removeAll function in my app. It works on iOS 15.7, but not on iOS 16+.
I've looked at the official developer documentation, and it doesn't mention any changes that could've happened in iOS 16+.
Further searching hasn't brought up any mention of this.
What has changed in iOS16+, that has caused this?
UPDATED QUESTION BELOW:
This method is called when user submits an answer to a question. The user's answer is stored as a string literal variable. The user's answer must be cleared from the screen whether the answer is correct or wrong.
I used another part of the app in iOS16+, which uses removeAll to empty an array. It emptied the array. I now suspect that removeAll should only be used on arrays. The user's answer in the code listing below should be assigned empty double quotes, instead of calling the removeAll method.
func checkAnswer() {
cancelDisabled = true
switchLanguageDisabled = true
attemptFinished = true
answered = true
if replaceApostrophesWithBackSlashes(userAnswer: userAnswer.allowedCharacters(string: userAnswer.trimmingCharacters(in: .whitespacesAndNewlines).lowercased())) == foreignNativeAnswer.allowedCharacters(string: foreignNativeAnswer.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()) {
aurotorial.speak(native: dataOps.removeEverythingInBrackets(nativeWord: nativeWordWithoutBrackets), foreign: dataOps.removeDashes(foreignWord: foreignWordWithoutDashes), language: (testSectionThings?[questionCounter].languageSection?.language)!, changeVoiceSpeed: changeVoiceSpeed ?? 0.25, maxLoops: numberSpeechLoops ?? 1)
updateWordCounters(correct: true)
userAnswer.removeAll()
languageColour = .green
showTapSkip = false
showNextTimeDisabled = true
let englishAnswerFont = UIFont.boldSystemFont(ofSize: 16)
let promptAttributes: [NSAttributedString.Key: Any] = [
.font: englishAnswerFont,
.foregroundColor: UIColor(red: 0, green: 0.7, blue: 0, alpha: 1)
]
languageText = NSAttributedString(string: foreignNativeAnswer, attributes: promptAttributes)
nativeForeignPlaceholder = NSMutableAttributedString(string: NSLocalizedString("Correct answer, well done!", comment: "Correct answer"))
DispatchQueue.main.asyncAfter(deadline: .now() + dataOps.determineTextToSpeechDelay(changeVoiceSpeed: changeVoiceSpeed ?? 0.25, numberForeignCharacters: foreignWordWithoutDashes.count)) {
self.prepareForNextQuestion()
}
} else {
updateWordCounters(correct: false)
yourAnswerPrompt = "Your answer: "
wrongAnswer = "\(userAnswer)"
userAnswer.removeAll()
foreignNativeAnswer.removeAll()
languageColour = .blue
showTapSkip = false
iKnowThisDisabled = false
let wrongAnswerFont = UIFont.boldSystemFont(ofSize: 16)
let wrongAnswerAttributes: [NSAttributedString.Key: Any] = [
.font: wrongAnswerFont,
.foregroundColor: UIColor(red: 0, green: 0, blue: 0.7, alpha: 1)
]
languageText = NSAttributedString(string: foreignNativeAnswer, attributes: wrongAnswerAttributes)
answerDisabled = true
let separator = NSMutableAttributedString(string: " ", attributes: noTestSectionThingsAttributes)
let tapAttributedString = NSMutableAttributedString(string: NSLocalizedString("Tap a blue button, then ", comment: "Answer field tap skip 1"), attributes: noTestSectionThingsAttributes)
let skipImageAttachment = NSTextAttachment()
skipImageAttachment.image = UIImage(named: "skip.png")?.withTintColor(.systemBlue)
let skipImageAttributedString = NSMutableAttributedString(attachment: skipImageAttachment)
let nextQuestionAttributedString = NSMutableAttributedString(string: NSLocalizedString(".", comment: "Answer field tap skip 2"), attributes: noTestSectionThingsAttributes)
let NSMutableAttributedStringArray = [tapAttributedString, skipImageAttributedString, nextQuestionAttributedString]
nativeForeignPlaceholder = NSMutableAttributedStringArray.join(withSeparator: separator)
}
enableHint()
enableSkip()
}

Am charts 4 LineSeries legend colors doesn't match graph colors

I have created a series chart using AmCharts version 4.
I have a red line that represents created cases and green line that represent closed cases. However my legend is blue for both lines. How can I get the legend color to fit the graph color?
I added color in the data section.
My code is here:
<script>
am4core.ready(function() {
var chart = am4core.create("chartdiv_cases_created_per_day", am4charts.XYChart);
chart.data = [
{
"x": "Mon 1",
"created_value": 1,
"created_color": am4core.color("red"),
"closed_value": 2,
"closed_color": am4core.color("green")
},
{
"x": "Tue 2",
"created_value": 4,
"created_color": am4core.color("red"),
"closed_value": 2,
"closed_color": am4core.color("green")
},
{
"x": "Wed 3",
"created_value": 3,
"created_color": am4core.color("red"),
"closed_value": 1,
"closed_color": am4core.color("green")
}
];
// Create axes
var categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());
categoryAxis.dataFields.category = "x";
var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
// Create series
var series1 = chart.series.push(new am4charts.LineSeries());
series1.dataFields.valueY = "created_value";
series1.dataFields.categoryX = "x";
series1.name = "Opprettet";
series1.propertyFields.stroke = "created_color";
series1.propertyFields.fill = "created_color";
series1.strokeWidth = 1;
series1.tooltipText = "Opprettet: {valueY}";
// Create series 2
var series2 = chart.series.push(new am4charts.LineSeries());
series2.dataFields.valueY = "closed_value";
series2.dataFields.categoryX = "x";
series2.name = "Lukket";
series2.propertyFields.stroke = "closed_color";
series2.propertyFields.fill = "closed_color";
series2.tooltipText = "Lukket: {valueY}";
// Legend
chart.legend = new am4charts.Legend();
chart.legend.labels.template.text = "[bold {color}]{name}[/]";
// Tooltips
chart.cursor = new am4charts.XYCursor();
chart.cursor.snapToSeries = series;
chart.cursor.xAxis = valueAxis;
}); // end am4core.ready()
</script>
<div id="chartdiv_cases_created_per_day" style="height: 300px;"></div>
Seems like you're combining data and js-objects. That might be what you want but I would perhaps suggest that you separate them, as it would make it easier that day you need to add data from server.
There is no need to include the color for each point. Most likely you want the same color for all the points in the same series.
That you can achieve like this:
series.stroke = am4core.color(color);
series.fill = am4core.color(color);
You have already named the series in the data as created_value and closed_value so we can easily make a function that adds the data, names the series' and colorize them :)
In which turn you just call
createSeries("created_value", "Created", "red");
createSeries("closed_value", "Closed", "green");
Full code (I'm sure there's more refactoring you could do):
am4core.useTheme(am4themes_animated); // Not needed, but looks cool ;)
// Create chart instance
var chart = am4core.create("chartdiv_cases_created_per_day", am4charts.XYChart);
// Add data
chart.data = [{
"date": new Date(2018, 0, 1),
"created_value": 362,
"closed_value": 699
}, {
"date": new Date(2018, 0, 2),
"created_value": 269,
"closed_value": 450
}, {
"date": new Date(2018, 0, 3),
"created_value": 700,
"closed_value": 358
}, {
"date": new Date(2018, 0, 4),
"created_value": 490,
"closed_value": 367
}, {
"date": new Date(2018, 0, 5),
"created_value": 500,
"closed_value": 485
}, {
"date": new Date(2018, 0, 6),
"created_value": 550,
"closed_value": 354
}, {
"date": new Date(2018, 0, 7),
"created_value": 420,
"closed_value": 350,
}];
// Create axes
var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
dateAxis.renderer.grid.template.location = 0;
dateAxis.renderer.minGridDistance = 30;
var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
// Create series
function createSeries(field, name, color) {
var series = chart.series.push(new am4charts.LineSeries());
series.dataFields.valueY = field;
series.dataFields.dateX = "date";
series.name = name;
series.tooltipText = "{dateX}: [b]{valueY}[/]";
series.strokeWidth = 2;
series.stroke = am4core.color(color);
series.fill = am4core.color(color);
// Set up tooltip
series.adapter.add("tooltipText", function(ev) {
var text = "[bold]{dateX}[/]\n"
chart.series.each(function(item) {
text += "[" + item.stroke.hex + "]●[/] " + item.name + ": {" + item.dataFields.valueY + "}\n";
});
return text;
});
series.tooltip.getFillFromObject = false;
series.tooltip.background.fill = am4core.color("#fff");
series.tooltip.label.fill = am4core.color("#00");
var bullet = series.bullets.push(new am4charts.CircleBullet());
bullet.circle.stroke = am4core.color("#fff");
bullet.circle.strokeWidth = 2;
return series;
}
createSeries("created_value", "Åpnet", "red");
createSeries("closed_value", "Lukket", "green");
chart.legend = new am4charts.Legend();
chart.cursor = new am4charts.XYCursor();
chart.cursor.maxTooltipDistance = 0;
<script src="//www.amcharts.com/lib/4/core.js"></script>
<script src="//www.amcharts.com/lib/4/charts.js"></script>
<script src="//www.amcharts.com/lib/4/themes/animated.js"></script>
<div id="chartdiv_cases_created_per_day"></div>

How to add dictionary values to images using SpriteKit?

(( EDIT 4: Successful in making cards flip. Using .contains on the node and running a SKAction sequence. How would I create three states for the card? Tuple sounds like a fun idea. Unflipped, Flipped, Flipped-Highlighted. It loads with all cards down (done), I want to unflip the card (done), then tap it again to highlight it. In doing so the second time, it highlights itself and the top guess word. The two strings are then concatenated in a label at the bottom, and a Next button activated (not built yet). Upon successful match of the key[value] == A[B] then Score += 1. Getting closer! ))
(( EDIT 3: Update of didMove with split keys and values. Can get the title to be the first key now and I can put the first value on the top left card okay as a test. Progress. Now I just need to either blank out the card on touch down or find a way to flip it. How would the touch down code be done? touch Began? ))
(( EDIT 2: Now thinking of it from the perspective of dictionary key value pairs rather than values alone. Gets rid of the problem of finding the key when the value is assigned to the card. Now to play with labelling the card with SKLabelNode. Need to flip card, add value, compare key. ))
(( EDIT: I made the elements all code in GameScene.swift . That file is now included in this post. Also updated question text and removed some other text. ))
I'm new to SpriteKit and Swift 3. With a few million speakers there's not a lot of Esperanto software so I want to make a game for myself to learn 1000 Esperanto words. (not shown!)
I want to have each card flip to reveal a word value from the dictionary key/values.
Then see if that word matches the wordGuess label key for the value selected.
Also JSON might be better for breaking up 1000 words into modular sections but I'll cross that bridge at another time.
// Code updated to EDIT 4
//
//
import SpriteKit
class GameScene: SKScene {
let guessLabel = SKLabelNode(fontNamed: "HelveticaNeue-UltraLight")
let anotherLabel = SKLabelNode(fontNamed: "HelveticaNeue-UltraLight")
var cardTopLeftLabel = SKLabelNode(fontNamed: "Arial-BoldMT")
let cardTopLeft = SKSpriteNode(imageNamed: "Redcard")
var cardTopRightLabel = SKLabelNode(fontNamed: "Arial-BoldMT")
let cardTopRight = SKSpriteNode(imageNamed: "Redcard")
var cardBottomLeftLabel = SKLabelNode(fontNamed: "Arial-BoldMT")
let cardBottomLeft = SKSpriteNode(imageNamed: "Redcard")
var cardBottomRightLabel = SKLabelNode(fontNamed: "Arial-BoldMT")
let cardBottomRight = SKSpriteNode(imageNamed: "Redcard")
var cardsDictionary: [String:String] = [
"tree": "arbo",
"forest": "arbaro",
"spider": "araneo",
"water": "akvo",
"watermelon": "akvomelono",
"school": "lerno",
"year": "jaro",
"grasshopper": "akrido",
"lawn": "gazono",
"friend": "amiko",
"people": "homoj",
"city": "urbo",
"mayor": "urbestro",
"movie": "filmo",
"Monday": "lundo",
"dog": "hundo"
]
// not used yet
func randomSequenceGenerator(min: Int, max: Int) -> () -> Int {
var numbers: [Int] = []
return {
if numbers.count == 0 {
numbers = Array(min ... max)
}
let index = Int(arc4random_uniform(UInt32(numbers.count)))
return numbers.remove(at: index)
}
}
func addLabel(spriteNode:SKSpriteNode, labelNode: SKLabelNode, cardValue: String, cardName: String) {
labelNode.zPosition = 1
labelNode.text = cardValue
labelNode.name = cardName //"cardTopRightLabel"
labelNode.fontSize = 40
labelNode.fontColor = .black
labelNode.position = CGPoint.init(x: cardTopLeft.size.width/4, y: 0.5)
labelNode.isHidden = true
spriteNode.addChild(labelNode)
}
override func didMove(to view: SKView) {
if let words = self.userData?.value(forKey: "words")
{
print("word information contains \(words)")
}
// get all the card keys
var cardKeys:[String] = []
for (k,_) in cardsDictionary {
cardKeys.append(k)
}
print("all keys are \(cardKeys)")
// slice for four card keys
var fourCardKeys = cardKeys[0...3]
print("four keys are \(fourCardKeys)")
// get keys for display
var firstCardKey = fourCardKeys[0]
var secondCardKey = fourCardKeys[1]
var thirdCardKey = fourCardKeys[2]
var fourthCardKey = fourCardKeys[3]
// print("Card Keys are \(firstCardKey), \(secondCardKey), \(thirdCardKey), \(fourthCardKey)")
// get the card values
var cardsValue:[String] = []
for (_,v) in cardsDictionary {
cardsValue.append(v)
}
print(cardsValue)
// slice for card values
let fourCardValues = cardsValue[0...3]
print(fourCardValues)
// get values for display
let firstCardValue = fourCardValues[0]
let secondCardValue = fourCardValues[1]
let thirdCardValue = fourCardValues[2]
let fourthCardValue = fourCardValues[3]
print("Card Values are \(firstCardValue), \(secondCardValue), \(thirdCardValue), \(fourthCardValue)")
// put first card key into label
guessLabel.zPosition = 1
guessLabel.text = firstCardKey //cardKeys[0]
guessLabel.name = "guessLabel"
guessLabel.fontSize = 144;
guessLabel.fontColor = .black
//anotherLabel.position = CGPoint(x:frame.midX, y:frame.midY - 100.0)
guessLabel.position = CGPoint(x:-2, y:233)
addChild(guessLabel)
anotherLabel.zPosition = 0
anotherLabel.text = "Guess key here, values in cards"
anotherLabel.name = "anotherLabel"
anotherLabel.fontSize = 45;
anotherLabel.fontColor = .blue
//anotherLabel.position = CGPoint(x:frame.midX, y:frame.midY - 100.0)
anotherLabel.position = CGPoint(x:-2, y:203)
addChild(anotherLabel)
////////////////
// top left card
cardTopLeft.zPosition = 0
cardTopLeft.size = CGSize(width: 300.0, height: 300.0)
cardTopLeft.anchorPoint = CGPoint(x: 0.5, y: 0.5)
cardTopLeft.position = CGPoint(x:-229, y:-57)
addChild(cardTopLeft)
addLabel(spriteNode: cardTopLeft,
labelNode: cardTopLeftLabel,
cardValue: firstCardValue,
cardName: "cardTopLeftLabel")
/////////////////
// top right card
cardTopRight.zPosition = 1
cardTopRight.size = CGSize(width: 300.0, height: 300.0)
cardTopRight.anchorPoint = CGPoint(x: 0.5, y: 0.5)
cardTopRight.position = CGPoint(x:132, y:-57)
addChild(cardTopRight)
addLabel(spriteNode: cardTopRight,
labelNode: cardTopRightLabel,
cardValue: secondCardValue,
cardName: "cardTopRightLabel")
///////////////////
// bottom left card
cardBottomLeft.zPosition = 1
cardBottomLeft.size = CGSize(width: 300.0, height: 300.0)
cardBottomLeft.anchorPoint = CGPoint(x: 0.5, y: 0.5)
cardBottomLeft.position = CGPoint(x:-225, y:-365)
addChild(cardBottomLeft)
addLabel(spriteNode: cardBottomLeft,
labelNode: cardBottomLeftLabel,
cardValue: thirdCardValue,
cardName: "cardBottomLeftLabel")
////////////////////
// bottom right card
cardBottomRight.zPosition = 1
cardBottomRight.size = CGSize(width: 300.0, height: 300.0)
cardBottomRight.anchorPoint = CGPoint(x: 0.5, y: 0.5)
cardBottomRight.position = CGPoint(x:132, y:-365)
addChild(cardBottomRight)
addLabel(spriteNode: cardBottomRight,
labelNode: cardBottomRightLabel,
cardValue: fourthCardValue,
cardName: "cardBottomRightLabel")
}
func touchDown(atPoint pos : CGPoint)
{
}
func touchMoved(toPoint pos : CGPoint) {
}
func touchUp(atPoint pos : CGPoint) {
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {
return
}
let touchLocation = touch.location(in: self)
let touchedNode = self.atPoint(touchLocation)
func flipCard (node: SKNode, label: SKLabelNode)
{
label.isHidden = true
node.run(SKAction.sequence(
[SKAction.scaleX(to: 0, duration: 0.2),
SKAction.scale(to: 1, duration: 0.0),
SKAction.setTexture(SKTexture(imageNamed: "Redcard-blank"))
]
))
label.isHidden = false
}
func flipCardPause (node: SKNode, interval: Double)
{
node.run(SKAction.wait(forDuration: interval))
print("paused for \(interval) seconds")
}
func flipCardBack (node: SKNode, label: SKLabelNode)
{
label.isHidden = true
node.run(SKAction.sequence(
[SKAction.scaleX(to: 1, duration: 0.2),
SKAction.setTexture(SKTexture(imageNamed: "Redcard"))
// SKAction.scale(to: 1, duration: 0.2)
]
))
}
if cardTopLeft.contains(touchLocation)
{
flipCard(node: cardTopLeft, label: cardTopLeftLabel)
//flipCardPause(node: cardTopLeft, interval: 3)
//flipCardBack(node: cardTopLeft, label: cardTopLeftLabel)
}
if cardTopRight.contains(touchLocation)
{
flipCard(node: cardTopRight, label: cardTopRightLabel)
}
if cardBottomLeft.contains(touchLocation)
{
flipCard(node: cardBottomLeft, label: cardBottomLeftLabel)
}
if cardBottomRight.contains(touchLocation)
{
flipCard(node: cardBottomRight, label: cardBottomRightLabel)
}
for t in touches { self.touchDown(atPoint: t.location(in: self)) }
}
How to assign dictionary values to the cards?. EDIT 2: By not using values! I'm going to do from the perspective of dictionary keys, that way each card has a key value pair, then just display the value.
// get all the card keys
var cardKeys:[String] = []
for (k,_) in cardsDictionary {
cardKeys.append(k)
}
// slice for only four cards
var fourCardKeys = cardKeys[0...3]
// get 1st value for display
cardsDictionary[fourCardKeys[0]]
So SKLabelNode on touchDown? I'll try it. Also need to flip card so word is not on the image. Lastly compare the pressed card's key to the wordGuess key text. Getting closer
EDIT 3: Update of didMove with split keys and values. Can get the title to be the first key now and I can put the first value on the top left card okay as a test. Progress. Now I just need to either blank out the card on touchDown or find a way to flip it.
cardTopLeft.zPosition = 0
cardTopLeft.size = CGSize(width: 300.0, height: 300.0)
cardTopLeft.anchorPoint = CGPoint(x: 0.5, y: 0.5)
cardTopLeft.position = CGPoint(x:-229, y:-57)
addChild(cardTopLeft)
cardTopLeftLabel.zPosition = 1
cardTopLeftLabel.text = fourCardValues[0]
cardTopLeftLabel.name = "cardTopLeftLabel"
cardTopLeftLabel.fontSize = 40
cardTopLeftLabel.fontColor = .black
cardTopLeftLabel.position = CGPoint.init(x: cardTopLeft.size.width/4, y: 0.5)
cardTopLeft.addChild(cardTopLeftLabel)
EDIT 4: Successful in making cards flip. Using .contains on the node and running a SKAction sequence. How would I create three states for the card? Tuple sounds like a fun idea. Unflipped, Flipped, Flipped-Highlighted. It loads with all cards down (done), I want to unflip the card (done), then tap it again to highlight it (help?). In doing so the second time, it highlights itself and the top guess word. The two strings are then concatenated in a label at the bottom, and a Next button activated (not built yet). Upon successful match of the key[value] == A[B] then Score += 1. Getting closer! It's really similar to just a matching game but I'm adding an extra layer of card flipping.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {
return
}
let touchLocation = touch.location(in: self)
let touchedNode = self.atPoint(touchLocation)
func flipCard (node: SKNode, label: SKLabelNode)
{
label.isHidden = true
node.run(SKAction.sequence(
[SKAction.scaleX(to: 0, duration: 0.2),
SKAction.scale(to: 1, duration: 0.0),
SKAction.setTexture(SKTexture(imageNamed: "Redcard-blank"))
]
))
label.isHidden = false
}
Personally, I don't like to use userData, my opinion is that isn't a readable code.
I'd some like to create a custom SKNode like:
class Card: SKSpriteNode {
var value....
var dictionary
etc
}
Another solution, you can create a tuples:
var cardsDictionary: [String:String] = [
"vegetable":"legomo",
"plant":"vegetalo",
"actually":"efektive",
"currently":"aktuale"
]
let cardTopLeft = (node:SKNode, value:Int, type:[String:String])
cardTopLeft.node = SKSpriteNode(imageNamed: "Redcard")
cardTopLeft.value = 1
cardTopLeft.type = cardsDictionary[0]
All SKNodes have a dictionary you can write to called userData. It is an optional NSMutableDictionary, so you are going to have to create it:
cardTopLeft.zPosition = 1
cardTopLeft.size = CGSize(width: 300.0, height: 300.0)
cardTopLeft.anchorPoint = CGPoint(x: 0.5, y: 0.5)
cardTopLeft.position = CGPoint(x:-229, y:-57)
cardTopLeft.userData = ["word":"tree","value","arbo"]
addChild(cardTopLeft)
To use:
let word = cardTopLeft.userData["word"]
let value = cardTopLeft.userData["value"]
Getting a better understanding of your question, I would use SKLabelNode as an alternative.
What you can do is create SKLabelNodes to the cards with the word you want to attach, and mark it as isHidden = true. When you are ready to reveal the word, you just mark isHidden = false
let value = SKLabelNode("arbo")
value.isHidden = false
cardTopLeft.zPosition = 1
cardTopLeft.size = CGSize(width: 300.0, height: 300.0)
cardTopLeft.anchorPoint = CGPoint(x: 0.5, y: 0.5)
cardTopLeft.position = CGPoint(x:-229, y:-57)
cardTopLeft.addChild(value)
addChild(cardTopLeft)
//to reveal it
if let label = cardTopLeft.children[0] as? SKLabelNode
{
label.isHidden = false
}
//to use it
if let label = cardTopLeft.children[0] as? SKLabelNode
{
let value = label.text
//compare value to dictionary of answers
}
You may want to give your labels a name so that you do not have to use children[0], but I will leave how you want to find a node up to you.

How to set selected segment background color using HMSegmentedControl in Swift 3.0

How can i achieve this style using HMSegmentedControl when the index is selected.Please help me how can i achieve this in swift 3.0 ......if it is possible
Here is my Code:
func setupSegementCategory(){
segmentCategory.sectionTitles = ["home","about","contract","home","about","contract"]
segmentCategory.backgroundColor = #colorLiteral(red: 0.7683569193, green: 0.9300123453, blue: 0.9995251894, alpha: 1)
segmentCategory.translatesAutoresizingMaskIntoConstraints = false
segmentCategory.selectionIndicatorLocation=HMSegmentedControlSelectionIndicatorLocation.down
segmentCategory.isVerticalDividerEnabled=false
segmentCategory.selectedSegmentIndex=0
segmentCategory.selectionIndicatorColor = UIColor.white
segmentCategory.segmentWidthStyle = HMSegmentedControlSegmentWidthStyle.dynamic
segmentCategory.titleTextAttributes = [
NSForegroundColorAttributeName : #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1),
NSFontAttributeName : UIFont.systemFont(ofSize: 17)
]
segmentCategory.backgroundColor=Constant.GlobalConstants.kColor_blue
segmentCategory.selectedTitleTextAttributes = [
NSFontAttributeName : UIFont.systemFont(ofSize: 17),
NSForegroundColorAttributeName :UIColor(red:0.74, green:0.70, blue:1.00, alpha:1.0)
]
segmentCategory.addTarget(self, action:#selector(segmentedControlValueChanged(sender:)), for: .valueChanged)
}
func segmentedControlValueChanged(sender: UISegmentedControl) {
let sortedViews = sender.subviews.sorted( by: { $0.frame.origin.x < $1.frame.origin.x } )
for (index, view) in sortedViews.enumerated() {
if index == sender.selectedSegmentIndex {
view.tintColor = UIColor.red
} else {
view.tintColor = UIColor.lightGray
}
}
}
There's currently no way to get that style in HMSegmentedControl.

Swift animatewithDuration() instantly completes

So, I have this code:
UIView.animate(withDuration: 10.0, delay: 0, options: .curveLinear , animations: {
self.gameLabel.alpha = 0
}, completion: nil)
The problem is when this code is called it instantly goes to a 0 alpha and doesn't slowly transition. What am I doing wrong?
Here is some more context for the the code:
var gameLabel = SKLabelNode()
override func didMove(to view: SKView) {
gameLabel.fontColor = UIColor.white
gameLabel.fontSize = 85
gameLabel.setScale(0.40)
gameLabel.text = "this is a game"
gameLabel.position = CGPoint(x: 0, y: 0)
gameLabel.zPosition = 0
gameLabel.alpha = 1
addChild(gameLabel)
}
func touchDown(atPoint pos : CGPoint) {
UIView.animate(withDuration: 2, animations: {
self.gameLabel.alpha = 0
})
}
So, i solved my problem by running.
self.gameLabel.run(SKAction.fadeOut(withDuration: 10))