Choose UIlabel background Color from Array and then remove it from array. (swift) - ios

I have 3 UiLabels onscreen. I have an array with colors e.g. red,green,blue. I want to set the background of each UiLabel to a a color in the array and then delete the Color from the array so no 2 UiLabels have the same Color.
I was trying to do something like this. it selects a random string in the array but then i cannot assign it to the uilabel because its not of type UIColor.
override func viewDidLoad() {
super.viewDidLoad()
let Colorarray = ["UIColor.redColor()", "UIColor.greenColor()", "UIColor.blueColor()"]
let randomIndex = Int(arc4random_uniform(UInt32(Colorarray.count)))
print(randomIndex)
self.left.text = (Colorarray[randomIndex])
self.left.backgroundColor = (Colorarray[randomIndex])
self.middle.backgroundColor = (Colorarray[randomIndex])
self.right.backgroundColor = (Colorarray[randomIndex])
}
this was the second code i tried
var colorArray = [(UIColor.redColor(), "Red"), (UIColor.greenColor(), "Green"), (UIColor.blueColor(), "Blue")]
//random color
let randomIndex = Int(arc4random_uniform(UInt32(colorArray.count)))
//accessing color
var (color, name) = colorArray[randomIndex]
self.left.text = name
self.left.backgroundColor = color
let leftColorRemoval = (colorArray.removeAtIndex(randomIndex))
print(leftColorRemoval)
var (mcolor, mname) = colorArray[randomIndex]
self.middle.text = mname
self.middle.backgroundColor = mcolor
let middleColorRemoval = (colorArray.removeAtIndex(randomIndex))
print(middleColorRemoval)
var (rcolor, rname) = colorArray[randomIndex]
self.right.text = rname
self.right.backgroundColor = rcolor
let rightColorRemoval = (colorArray.removeAtIndex(randomIndex))
print(rightColorRemoval)

You can store an array of tuples that include both the actual UIColor and the string value. This makes it so you can provide any string value you want:
let colorArray = [(UIColor.redColor(), "Red"), (UIColor.greenColor(), "Green"), (UIColor.blueColor(), "Blue")]
Then, to access a random color:
let (color, name) = colorArray[randomIndex]
self.left.text = name
self.left.backgroundColor = color
...
It seems to me that your code doesn't actually remove random colors. Here's how you would actually do it (one of many ways):
let random = { () -> Int in
return Int(arc4random_uniform(UInt32(colorArray.count)))
} // makes random number, you can make it more reusable
let (leftColor, leftName) = colorArray.removeAtIndex(random()) // removeAtIndex: returns the removed tuple
let (middleColor, middleName) = colorArray.removeAtIndex(random())
let (rightColor, rightName) = colorArray.removeAtIndex(random())

Related

How can I fix error multiple colors of BarChart in Swift?

I have a bar chart to show item using Chart library. I got an error that the explain description show multiple colors for each item. Please help me how can i fix this, i want to show exactly the color like column (only one color), not multiple like this. Thanks for your helping.
My Screen
Here is my code, note that items is dynamic, i got from API:
func setDataCount(items: [Item]) {
let dataEntry = (0..<items.count).map { (i) -> ChartDataEntry in
let value = Double(items[i].soldQuantity)
return BarChartDataEntry(x: Double(i), y: value)
}
var arrayDataSet = [IChartDataSet]()
var arrayColor = [UIColor]()
var set = BarChartDataSet()
for i in 0...items.count - 1 {
set = BarChartDataSet(entries: dataEntry, label: items[i].name)
arrayColor.append(UIColor.random)
set.colors = arrayColor
// CONVERT DOUBLE -> INT
set.valueFormatter = DefaultValueFormatter(decimals: 0)
arrayDataSet.append(set)
}
let data = BarChartData(dataSets: arrayDataSet)
data.setValueFont(.systemFont(ofSize: 10, weight: .bold))
data.barWidth = 0.2
chartView.data = data
}

Randomized String & UIImageView together

I'm working on an app which lets users have randomized data when you shake your device.
I have 4 arrays to hold the string data and function which creates randomized number;
let characters = ["Zoolog", "Xander"]
let problems = ["Asteroid", "Dr Evil"]
let places = ["Vast Desert", "Ice Caves"]
let time = ["Wednesday 12th, 1220", "1236"]
func randomCharacter() -> String {
let randomNumber = GKRandomSource.sharedRandom().nextInt(upperBound: characters.count)
return characters[randomNumber]
}
func randomPlaces() -> String {
let randomNumberOne = GKRandomSource.sharedRandom().nextInt(upperBound: places.count)
return places[randomNumberOne]
}
func randomProblems() -> String {
let randomNumberTwo = GKRandomSource.sharedRandom().nextInt(upperBound: problems.count)
return problems[randomNumberTwo]
}
func randomTime() -> String {
let randomNumberThree = GKRandomSource.sharedRandom().nextInt(upperBound: time.count)
return time[randomNumberThree]
}
On my viewController, data is randomized and users get a randomized data on their screen once they shake their devices.
override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
if(event?.subtype == UIEventSubtype.motionShake) {
characterName.text = myStoryCharacters.randomCharacter()
placeName.text = myStoryCharacters.randomPlaces()
problemName.text = myStoryCharacters.randomProblems()
timeName.text = myStoryCharacters.randomTime()
}
}
I also have an imageView for the character picture. So once the data is randomized I would like my users to see the characters and their names as well. But at the moment, I can only randomize the imageView and characters separately not together.
I've gone through some sample codes but couldn't understand how to approach this.
--Updated
Note: I don't have a problem with the code I have. I don't know how to randomize the characterImageView to match with the characterName. So if a picture belongs to a character in my character array then the nameLabel and imageView should match.
override func viewDidLoad() {
super.viewDidLoad()
super.becomeFirstResponder()
// Do any additional setup after loading the view, typically from a nib.
characterImageView.image = UIImage(named: "elegantEmma")
placeImageView.image = UIImage(named: "zombieLand")
problemImageView.image = UIImage(named: "meteor")
timeImageView.image = UIImage(named: "time")
//First random value shown on the launch
characterName.text = myStoryCharacters.randomCharacter()
placeName.text = myStoryCharacters.randomPlaces()
problemName.text = myStoryCharacters.randomProblems()
timeName.text = myStoryCharacters.randomTime()
You need to store the image names in arrays as well, so for example for your characters have...
let characters = ["Zoolog", "Xander"]
let characterImages = ["ZoologImage", "XanderImage"] // These relate to the image names in your assets
func randomCharacter() -> String {
let randomNumber = GKRandomSource.sharedRandom().nextInt(upperBound: characters.count)
characterImageView.image = UIImage(named: characterImages[randomNumber])
return characters[randomNumber]
}
Then do the same for the other arrays, you could also change the random functions to set the text and not bother returning it, unless of course you need it for something else

turn string into a UIColor swift

I have buttons filled with Colors: enter image description here
When user press on a color, a string is generated, i.e.
Yellow or Blue or Black etc.
What i want is to load the string into a UIColor when i segue back:
garageNameLabel.backgroundColor = UIColor."THE STRING THAT WAS GENERATED"
I know that UIColor.whiteColor(), blackColor() is there.
code:
let theStringColor = Blue
garageNameLabel.backgroundColor = UIColor.theStringColor
Thanks
I solved the problem by making a dictionary
var colors : [String:UIColor] = ["White": UIColor.whiteColor(), "Black":
UIColor.blackColor(), "Gray": UIColor.grayColor(),"Turquoise":
UIColor.cyanColor(),"Red":
UIColor.redColor(),"Yellow":UIColor.yellowColor(),"Blue": UIColor.blueColor(),
"Green": UIColor.greenColor()]
and then loading the string into it i.e.:
let theStringColor = "Blue"
garageNameLabel.backgroundColor = colors[theStringColor]
In OBJC code like this works. i have not tested this code, only translated it from OBJC to swift.
private func setColorWithNameForLabel(label: UILabel, colorName: String) {
let colorString = colorName + "Color" // if your colorName matches f.i. "black" --> blackColor
let s = Selector(colorString)
if let color = UIColor.performSelector(s).takeUnretainedValue() as? UIColor { // as of swift 2.0 you have to take the retained value
label.textColor = color
}
}
You can pass a parameter in the segue. In the new view, in the viewDidLoad () function, you can perform a check that change color depending on the value of the parameter.
if parameter == "blue" {
garageNameLabel.backgroundColor = UIColor.blueColor ()
} Else if parameter == "green" {
garageNameLabel.backgroundColor = UIColor.greenColor ()
}

Function that returns an Array from an Array of Arrays

Im trying to make a function that takes in an Array of Arrays that returns a single Array so that all values ("names") have there own index.
var namesList1 = [String]()
var namesList2 = [String]()
var namesList3 = [String]()
namesList1 = ["Paul","John","Ringo","George"]
namesList2 = ["Julie","Sarah","Jackie"]
namesList3 = ["Jim","Jack","Charlie","Sally","Debra"]
var namesCombinedArray = [NSArray]()
namesCombinedArray = [namesList1,namesList2,namesList3]
func total(arrays:NSArray) -> NSArray{
// how to loop to create an array with index(s) to all names ??
var completeList = [NSArray]()
return completeList
}
You could use flatMap:
let namesList1 = ["Paul","John","Ringo","George"]
let namesList2 = ["Julie","Sarah","Jackie"]
let namesList3 = ["Jim","Jack","Charlie","Sally","Debra"]
let namesCombinedArray = [namesList1,namesList2,namesList3]
let completeList = namesCombinedArray.flatMap{$0}
print(completeList)
// [Paul, John, Ringo, George, Julie, Sarah, Jackie, Jim, Jack, Charlie, Sally, Debra]

Usage for plotAreaViewPointForPlotPoint in CorePlot 1.5.1

I'm trying to add something like UIPopoverController into the barPlot with coreplot 1.5.1 and swift. Like this one Core Plot: How to present popover from a bar selected by the user
So we need to know the point where the selected bar is ,But looks like some functions are different, like plotAreaViewPointForPlotPoint. In 1.5.1, there are two parameters:
And I'm try to find the right way to use it but failed, here is my code:
func barPlot(plot: CPTBarPlot!, barWasSelectedAtRecordIndex idx: UInt, withEvent event: UIEvent!) {
// Remove all the annotations
graphView.hostedGraph.plotAreaFrame.plotArea.removeAllAnnotations()
// Setup a style for the annotation
let hitAnnotationTextStyle = CPTMutableTextStyle.textStyle() as! CPTMutableTextStyle
hitAnnotationTextStyle.color = CPTColor.whiteColor()
hitAnnotationTextStyle.fontSize = 12.0;
hitAnnotationTextStyle.fontName = FONT_HEITI;
// Determine point of symbol in plot coordinates
let anchorPoint = [Int(idx),0]
// Add annotation
// First make a string for the y value
let string = "\(idx),values is:\(mArray.objectAtIndex(Int(idx)))"
// Now add the annotation to the plot area
let textLayer = CPTTextLayer(text: string, style: hitAnnotationTextStyle)
// popview, DxPopover is something like UIPopover Controller in iPhone
var popView = DXPopover()
annotationLabel.text = string
var pointers = [NSDecimal](count: 2, repeatedValue: CPTDecimalFromUnsignedInteger(0))
pointers[0] = CPTDecimalFromUnsignedInteger(idx)
var plotPointer: UnsafeMutablePointer<NSDecimal> = UnsafeMutablePointer<NSDecimal>.alloc(pointers.count)
plotPointer.initializeFrom(pointers)
var popPoint = graphView.hostedGraph.defaultPlotSpace.plotAreaViewPointForPlotPoint(plotPointer, numberOfCoordinates: idx)
popView.showAtPoint(popPoint, popoverPostion: DXPopoverPosition.Down, withContentView: self.annotationView, inView: graphView)
// selectedBarAnnotation = CPTPlotSpaceAnnotation(plotSpace: graphView.hostedGraph.defaultPlotSpace, anchorPlotPoint: anchorPoint)
// selectedBarAnnotation!.contentLayer = textLayer
// selectedBarAnnotation!.displacement = CGPointMake(0.0, -15.0)
// graphView.hostedGraph.plotAreaFrame.plotArea.addAnnotation(selectedBarAnnotation)
}
And it will crush at this line:
var popPoint = graphView.hostedGraph.defaultPlotSpace.plotAreaViewPointForPlotPoint(plotPointer, numberOfCoordinates: idx)
SO, HOW CAN I GET THE RIGHT CGPOINT?
Thanks very much!
=================EDIT===================
I change my codes to this, and can get the right point, Thanks to #Bannings
var popView = DXPopover()
annotationLabel.text = string
var pointers = [NSDecimal](count: 2, repeatedValue: CPTDecimalFromUnsignedInteger(0))
let plotXvalue = self.numberForPlot(plot, field: UInt(CPTScatterPlotFieldX.value), recordIndex: idx)
pointers[0] = CPTDecimalFromFloat(plotXvalue.floatValue)
println("\(CPTDecimalFromUnsignedInteger(idx))")
let plotspace = graphView.hostedGraph.defaultPlotSpace
println("\(plotspace.numberOfCoordinates)")
var popPoint = plotspace.plotAreaViewPointForPlotPoint(&pointers, numberOfCoordinates: plotspace.numberOfCoordinates)
popView.showAtPoint(popPoint, popoverPostion: DXPopoverPosition.Down, withContentView: self.annotationView, inView: graphView)
Try this:
var popPoint = graphView.hostedGraph.defaultPlotSpace.plotAreaViewPointForPlotPoint(&pointers, numberOfCoordinates: idx)

Resources