How to change background colour of an element at index of array? - arrays

I want to create a drop down like this:
.
I have an string array as datasource of an drop down menu.I want to give background to element at 3rd index of an array.
I have tried it in doing all things possible but not able to find out any solution.

If you insert your values to list of UIButtons (let btns : [UIButton] = [btn0, btn1, btn2, btn3]), you can do that:
for i in 0..<btns.count {
if i == 2 {
btns[i].backgroundColor = .red
}
}
or just find needed UI-element and set needed color.

You need to create an array of similar size as your dataSource and this is only if you can't add a property of the color
var arr = [UIColor]()
arr = [.red,.green,.blue]
arr[2] = .orange

Related

Swift - Update and store position of a multiple programmatically created buttons

I have a button which creates other buttons based on the class Clip seen below. Those newly created buttons are added to an array and stored in a plist.
class Clip: Encodable, Decodable {
var name: String = ""
var xCoordinate: Int = 100
var yCoordinate: Int = 300
// more parameter will be added later on e.g color, scale etc..
}
Each button can be moved around the view and the new x & y coordinates are stored in a plist.
#objc func handlePan(sender: UIPanGestureRecognizer){
let uIViewSelected = sender.view!
switch sender.state {
case .began, .changed :
moveViewWithPan(view: uIViewSelected, sender: sender)
break
case .ended:
//Finds the position when the button is no longer being dragged
let x = Int(uIViewSelected.center.x)
let y = Int(uIViewSelected.center.y)
//clipArray[0] need to be the corresponding clicked button e.g clipArray[2]
clipArray[0].xCoordinate = x
clipArray[0].yCoordinate = y
saveData()
break
default:
break
}
}
The above works only if I create one button. When more buttons are added, the above lines only change the first clip from the array. I need a way to update the value to the correct button clicked.
How can identify the array position of the click button as I am creating all them programmatically? At the moment I am placing at value 0 of the clipArray.
clipArray[0].xCoordinate = x
clipArray[0].yCoordinate = y
I am not even sure if using a plist is the best way to store the buttons in the first place.
Any help or documentation would be much appreciated.
Thanks
Following from dfd response, I added tags to each button which are created and it solved the issue for now.
let x = Int(uIViewSelected.center.x)
let y = Int(uIViewSelected.center.y)
//clipArray.append(clip)
var tagNo = uIViewSelected.tag
clipArray[tagNo].xCoordinate = x
clipArray[tagNo].yCoordinate = y

I am trying to make a json array after getting each records from a grid. I want to add row number of grid as key of each row in json array

I am trying to make a json array after getting each records from a grid in ExtJS 3.4.0. I want to add row number of grid as key of each row in JSON array.
var selected_value = [];
for (var i = 0; i < count; i++)
{
var rec = store.getAt(i);
selected_value[i] = rec.data;
final.push({
"i":selected_value[i],
})
}
What you do there is build an array of objects with each object containing one property called i and that property has the value of the row in it.
I guess you actually just wanted to have an array with the row objects in it, right?
final.push(selected_value[i]);
This will do the job already. No need to specify an object with associative indices.
If you're grabbing all the store's entries already or at least know the range (start and end index) you could just as well skip all the manual item picking and grab a readymade array already:
final = store.getRange();
or
final = store.getRange(from, to);

How to insert new item in empty array any position?

i have a table that is multiple selected allow. first time user select some row . second time user come beck this page deselect some row and may be selected some row or not . but i need to hold previous selected rows . that row indicated price . so i need to track price that is the reason table view selected row i am tracking .
Here i my declaration array empty :
var groupSelectedOldPrice : [String] = []
here is my table row selected index item price append to the array:
if addon?.isSelect == true {
cell.accessoryType = .checkmark
groupSelectedOldPrice[indexPath.row] = (addon?.price)! // Index out of range
}
when user press done button :
let selectedUserRows = self.tableView.indexPathsForSelectedRows
if let _selectedUserRows = selectedUserRows {
for select in _selectedUserRows {
print(select.row)
let dishprice = Double((dish?.price)!)! - Double(groupSelectedOldPrice[select.row])!
dish?.price = "\(dishprice)"
}
}
i am not sure How i can achieved this . should I use dictionary for key value
You are getting Array index is out of range error because you are trying to insert at discrete indexes (more like skipping intermediate indexes. But it doesn't work this way. You just can't have an array like ["a", "b", _ , _ , "g", "u", _ , _ , "y"])
Let's do one thing. You maintain a counter var, insert at that counter's position and then increment that counter. Something like:
var counter: Int = 0
...
groupSelectedOldPrice.insert("your string" at:counter)
counter = counter +1
...
EDIT
(Answered according to what you asked for)
To achieve your requirement, you can maintain a Dictionary. A Dictionary where key will be your indexpath.row and value will be your String. Pretty much like:
var dic: [Int:String] = [:] // it's your declaration
....
....
dic[indexpath.row] = "your string" // when you try to fill your dictionary
You can insert your element at a specific index of array
let index = 1
yourArray.insert("Your String", at: index)

swift - using .map on struct array

i have a struct array that i want "break up" into smaller arrays that can be called as needed or at least figure out how i can map the items needed off one text value.
the struct:
struct CollectionStruct {
var name : String
var description : String
var title : String
var image : PFFile
var id: String
}
and the array made from the struct
var collectionArray = [CollectionStruct]()
var i = 0
for item in collectionArray {
print(collectionArray[i].name)
i += 1
}
printing partArray[i].name gives the following result:
pk00_pt01
pk00_pt02
pk00_pt03
pk01_pt01
pk01_pt02
pk01_pt03
pk01_pt04
pk01_pt05
pk01_pt06
pk01_pt07
pk01_pt08
this is just some test values but there could be thousands of entries here so i wanted to filter the entire array just by the first 4 characters of [i].name i can achieve this by looping through as above but is this achievable using something like .map?
I wanted to filter the entire array just by the first 4 characters of
[i].name
You can achieve this by filtering the array based on the substring value of the name, as follows:
let filteredArray = collectionArray.filter {
$0.name.substring(to: $0.name.index($0.name.startIndex, offsetBy: 4)).lowercased() == "pk00"
// or instead of "pk00", add the first 4 characters you want to compare
}
filteredArray will be filled based on what is the compared string.
Hope this helped.
If you want to group all data automatically by their name prefix. You could use a reducer to generate a dictionary of grouped items. Something like this:
let groupedData = array.reduce([String: [String]]()) { (dictionary, myStruct) in
let grouper = myStruct.name.substring(to: myStruct.name.index(myStruct.name.startIndex, offsetBy: 4))
var newDictionart = dictionary
if let collectionStructs = newDictionart[grouper] {
newDictionart[grouper] = collectionStructs + [myStruct.name]
} else {
newDictionart[grouper] = [myStruct.name]
}
return newDictionart
}
This will produce a dictionary like this:
[
"pk00": ["pk00_pt01", "pk00_pt02", "pk00_pt03"],
"pk01": ["pk01_pt01", "pk01_pt02", "pk01_pt03", "pk01_pt04", "pk01_pt05", "pk01_pt06", "pk01_pt07"],
"pk02": ["pk02_pt08"]
]
Not sure if i am understanding you correctly but it sounds like you are looking for this...
To create a new array named partArray from an already existing array named collectionArray (that is of type CollectionStruct) you would do...
var partArray = collectionArray.map{$0.name}

Array whose each clip is linked to its equal clip of another array

Hello I apologize in advance for my question which I'm sure is pretty basic.
On a map are set 33 landmarks with an array calling a class in the library.
A second array defines the coordinates of those landmarks.
for (var i:uint = 0; i < 33; i++) {
mark[i] = new landMark();
landMarks.addChild(mark[i]);
mark[i].x = lmxy[i]['x'];
mark[i].y = lmxy[i]['y'];
}
var lmxy:Array = [{x:1620,y:880},{x:1850, y:1050},etc...];
So far so good, the landmarks show each in its right place.
The third array contains different legends supposed to show when a landmark is clicked.
So the landmark [1] should show the legend [1] and the landmark [31] the legend [31]
var lgd:Array = [lgdA, lgdB, etc... ];
var legends:MovieClip;
for (var j:uint=0;j<lgd.length;j++) {
legends = new lgd[j]();
legends.x = 300;legends.y = 170;
}
Edit cause obviously that was unclear :
I tried that in the loop to link the marks to the legends but I get an error :
mark[i].addEventListener(MouseEvent.CLICK, getLgd);
function getLgd(e:Event):void {stage.addChild (lgd[i]);}
Any help would be very welcome !
The problem is that the variable i doesn't have a definition. The only way for you to find out which of the landmarks were clicked is to find its index in the array, then you can add the legend that has the same index. Because the index isn't passed from the event listener, you need to use e which has the target property.
This should do the trick:
mark[i].addEventListener(MouseEvent.CLICK, getLgd);
function getLgd(e:Event):void
{
var i:int = mark.indexOf(e.target);
stage.addChild(lgd[i]);
}

Resources