Get values from a textfield array - arrays

I would like to access the values of my textfield array but confused as the array I created is with tags.
So anyone knows how to get the value of the list (array) I created?
I want to create a function where I :
Get the value of the textfields on a list
Sort them by tags
get the value of each individual textfield
concatenate them in a string

1.Your collection Outlet will be something like this
#IBOutlet var textFields: [UITextFields]!
2. Sort it by tag
textFields.sort { $0.tag < $1.tag}
3. Use for loop to get value from array and concatenate it
var string = ""
for item in textFields {
string += item.text
}

Let's say you have following array,
var txtArray:[UITextField] = [UITextField]()
for i in 0...4 {
let txtField = UITextField(frame: .zero)
txtField.text = "\(i)"
txtField.tag = i
txtArray.append(txtField)
}
To get values you have to do following,
let sorted = txtArray.sorted { $0.tag < $1.tag }
let values = sorted.map { return $0.text! }
let test = values.joined(separator: " ")
print(test)
Output will be
0 1 2 3 4

Create an outlet connection and connect all your textfields to the same.
An outlet connection looks like
#IBOutlet strong var labels: [UILabel]!
Then to get all textfield contents and to append the same.
var resultString = ""
for item in enumerate(self.labels) {
resultString = resultString + item.text
}

Assume that you have array of UITextField
let textfield1 = UITextField()
textfield1.tag = 1
textfield1.text = "1"
let textfield2 = UITextField()
textfield2.tag = 2
textfield2.text = "2"
let textfield3 = UITextField()
textfield3.tag = 3
textfield3.text = "3"
let arrayOfTextFields :[UITextField] = [textfield2,textfield1,textfield3]
let result = self.getInputsValue(arrayOfTextFields, seperatedby: "-")
print(result)
Method you want :
func getInputsValue(_ inputs:[UITextField], seperatedby value: String) -> String {
return inputs.sorted {$0.tag < $1.tag}.map {$0.text}.compactMap({$0}).joined(separator: value)
}
Result:
1-2-3

Related

How can I merge 2 dictionaries into one array?

My JSON data look like this image below. Now I wanna merge the value of Shop Type and Promotion into one to use as collection view data. How can I do that?
I just filter the response data from the server like this:
var dataBanDau: [SDFilterModel] = []
var quickData: [SDFilterModel] = []
let filters: [SDFilterModel] = data
self.filterEntries = filters
//let nsarray = NSArray(array: self.filterEntries! , copyItems: true)
// self.filterEntriesStoreConstant = nsarray as! Array
self.dataBanDau = filters
for i in 0..<self.dataBanDau.count {
if self.dataBanDau[i].search_key.count == 0 {
self.quickData.append(self.dataBanDau[i])
}
}
self.quickData = self.quickData.filter {
$0.type != "range"
}
DispatchQueue.main.async {
//Note: Reload TableView
self.quickFilterCollection.reloadData()
completed(true)
}
}
the class SDFilterModel:
class SDFilterModel: DSBaseModel {
var name = String()
var type = String()
var is_expanded = Int()
var search_key = String()
var filterEntries : [SDFilterModel]?
override func copy(with zone: NSZone? = nil) -> Any {
// This is the reason why `init(_ model: GameModel)`
// must be required, because `GameModel` is not `final`.
let copy = SDFilterModel(dict: self.dictionary)
if let arrAttribute = NSArray(array: self.value , copyItems: true) as? [AttributeValueModel] {
copy.value = arrAttribute
}
return copy
}
override init(dict: Dictionary<String, Any>) {
super.init(dict: dict);
value = self.valueParse()
name = dict.getString(forKey: "name")
type = dict.getString(forKey: "type")
search_key = dict.getString(forKey: "search_key")
is_expanded = dict.getInt(forKey: "is_expanded")!
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
var value: [AttributeValueModel] = [];
func valueParse()-> [AttributeValueModel] {
guard let childs = (self.dictionary["value"]) as? [Dictionary<String, AnyObject>]
else { return [] }
var output: [AttributeValueModel] = [];
for aDict in childs {
let item = AttributeValueModel(dict:aDict);
// if type == .Range && item.option_id == "0" {
// item.setRangeOptionID(aValue: item.option_name!)
// }
//
output.append(item);
}
return output;
}
Let be Assume you have let myArray = [1,2,3,4,5,6,7,8]
Now you wanted to square of each and every element in the array,
With for loop you do like this
for item in myArray {
print(item * item)
}
Now assume item = $0
With for map you jus do
myArray.map({ $0 * $0 })
Both will gave same output.
map : Use to do same operation on every element of array.
flatmap : It is used to flattern the array of array.
let myArr = [[1,2,3],[4,5,6,7]]
and you want o/p as [1,2,3,4,5,6,7]
So can get above output with myArr.flatMap({$0})
Now back to your question.
let reqArray = myModel.data.map({ $0.value }).flatMap({ $0 })
First, map gaves you array-of-array of key value but you need a single array, so for that you need to use flatmap.
You can take ref : https://medium.com/#Dougly/higher-order-functions-in-swift-sorted-map-filter-reduce-dff60b5b6adf
Create the models like this
struct Option {
let name: String
let searchKey: String
let id: String
}
struct Model {
let type: String
let name: String
let isExpanded: Bool
let value: [Option]
}
You should get the options array values and join all the arrays
let models:[Model] = //...
let collectionViewArray = models.map { $0.value }.reduce([Option](), +)
Using for loop
var collectionViewArray = [Option]()
for model in models {
collectionViewArray.append(contentsOf: model.value)
}

How do I check if each UITextField in an Array has a user input?

I have a list of UITextFields in an Array for users to key in phone numbers. When I click the Send Button, it will connect with my server to send an automated message to the numbers listed. This portion works well. What I want to do now is to check which of the UITextFields has a phone number in it and to check if it has the prefix + before it connects to my server. If any of the UITextField has a phone number without the prefix +, the border color of that UITextField should change colours. If the UITextField does not have a phone number, no action should be taken. How do I go about achieving that?
This is the portion of the code that I need help in
#IBAction func sendbutton(_ sender: Any) {
var numArray: Array<Any>
numArray = [phonenumber.text!, phonenumber1.text!, phonenumber2.text!, phonenumber3.text!]
let myColor = UIColor.red
for num in numArray {
if (num as AnyObject).hasPrefix("+") {
print("Has + symbol")
} else {
print("Does Not Have Symbol")
}
}
You can traverse over the array of textFields and for each textField validate the text for first character is "+". If not set its borderColor.
var textFields = [phonenumber, phonenumber1, phonenumber2, phonenumber3]
var numArray = [String]()
textFields.forEach {
if let text = $0.text, text.first == "+" {
numArray.append(text)
$0.layer.borderWidth = 0.0 //To reset the textField if it didn't validate earlier
} else {
$0.layer.borderColor = UIColor.red.cgColor
$0.layer.borderWidth = 1.0
}
}
I don't think you should loop over an array of strings, instead loop over the text fields so you can set the color directly
var textFields: Array<UITextField> = [phonenumber, phonenumber1, phonenumber2, phonenumber3]
var numbersToSend = [String]()
let myColor = UIColor.red
for textField in textFields {
let number = textField.text ?? ""
if validatePhoneNumber(number) { //extract validation into separate function for clarity
numbersToSend.append(number)
} else {
textField.backgroundColor = myColor //or whatever property you want to change
}
}
Please try this solution i'll work.
private var arrTextFilds = [phonenumber.text ?? "", phonenumber1.text ?? "",
phonenumber2.text!, phonenumber3.text ?? ""]
private var numArray : [String] = []
arrTextFilds {
if let text = $0.text,text.hasPrefix(“+”) {
numArray.append(text)
$0.layer.borderWidth = 0.0
} else {
$0.layer.borderColor = UIColor.red.cgColor
$0.layer.borderWidth = 1.0
}
}

Swift- How to add onto arraylist next index everytime save button is pressed

Hi my question is how can I store a string value which contails all textfield input into an array with new index every time I press save. I have created some code below however I think its overriding the first index.
#IBAction func Save (_ sender: UIButton){
let firstextfield = textfield1.text
let secondtextfield = textfield2.text
let allText = firsttextfield! + "," + secondtextfield!
var myArray = [String]()
var index : Int = 0
while (myArray.count) <= index {
myArray.insert(allText, at: index)
}
index +=
for element in myArray{
print(element)
}
}
input: firsttextfield = 9.22 and secondtextfield = 91.2
save button is then pressed.
output:
Optional ("9.22,91.2")
Optional ("")
if i were to then change the values of my textfields to firsttextfield = 0.2 and secondtextfield = 20.2
I get output :
Optional ("0.2,20.2")
Optional ("")
I dont want it to overide the array but to add onto it so expected output:
Optional ("9.22,91.2")
Optional ("0.2,20.2")
Any tips are welcome as I am new to coding.
//Just Declare outside of button action
var index = 0
var myArray = [String?]()
//Button action
#IBAction func btnShareTapped(_ sender: UIButton) {
let firstextfield = "textfield1.text"
let secondtextfield = "textfield2.text"
let allText = firstextfield + "," + secondtextfield
while (myArray.count) <= index {
myArray.append("")
}
myArray.insert(allText, at: index)
index = index + 1
for element in myArray{
print(element)
}
print(myArray)
}
Output
[Optional("textfield1.text,textfield2.text"), Optional("")]
[Optional("textfield1.text,textfield2.text"), Optional("textfield1.text,textfield2.text"), Optional("")]
//your last comment answer is
let a : String = myArray[0]!
let b = a.split(separator: ",")
label.text = b[0] as! String
label1.text = b[1] as! String
I think your emptying the array here:
var myArray = [String?]()
var index = 0
while (myArray.count) <= index {
myArray.append("")
}
declare and initialise it outside the function and then use this to insert values to array:
let allText = firsttextfield! + "," + secondtextfield!
anArray.append(allText)

How to delete specific NSObject in Array with Swift3

I made table view with friends contact info.
And Each cell has button if touched,
I want to insert the info to selected friend array
(by the array, I made another small view to slide up with the friends list).
But If user the button one more,
I want to delete the friend Info in the selected friend array.
I know how to append to array,
but I don't know how to erase the specific item(NSObject) in array
by not using index.
my source code is below
class FriendModel : NSObject {
dynamic var index : ""
dynamic var thumbnail : ""
dynamic var name : ""
}
and In view controller class,
var selectedList = [FriendModel]()
#IBAction func SelectAct(_ sender: Any) {
let chooseBtn = sender as! UIButton
let indexPath = NSIndexPath(row: chooseBtn.tag, section:0)
let cell = tableView.cellForRow(at: indexPath as IndexPath) as! FriendsListSendCell
// when selected button is pushed
if chooseBtn.isSelected == true {
chooseBtn.isSelected = false
count = count! - 1
if self.count! < 1 {
self.windowShowUp = false
UIView.animate(withDuration: 0.1, delay: 0.1, options: [], animations:{self.selectedBoard.center.y += 80 }, completion: nil)
self.checkNumLabel.text = ""
}else{
}
//////////////////////////here////////////////////////////
//////////////////how to erase the FriendModel(NSObject) in selectedList.
}
//when the unselected button is pushed
else {
//instance for append the friend info
let friendInfo = FriendModel()
chooseBtn.isSelected = true
count = count! + 1
friendInfo.thumbnail = cell.thumbnail
friendInfo.name = cell.nameLabel.text!
//add friend info to selectedList
self.selectedList.append(friendInfo)
print("\(self.selectedList)")
if self.windowShowUp! == false{
self.windowShowUp = true
UIView.animate(withDuration: 0.1, delay: 0.1, options: [], animations:{self.selectedBoard.center.y -= 80 }, completion: nil)
}else{
}
}
}
You can use index(where:) to get index of your object and then remove item at index position.
class FriendModel {
var index = ""
var thumbnail = ""
var name = ""
}
let fm0 = FriendModel()
fm0.index = "100"
fm0.thumbnail = "tell.png"
fm0.name = "Phillips"
let fm1 = FriendModel()
fm1.index = "200"
fm1.thumbnail = "ask.png"
fm1.name = "Allen"
var array = [FriendModel]()
array.append(fm0)
array.append(fm1)
// The index below is an index of the array. Do not confuse with the FriendModel.index
let index = array.index {
return $0.thumbnail == "ask.png" && $0.name == "Allen"
}
array.forEach { print($0.name) }
print("Array index:", index ?? "n/a")
array.remove(at: index!)
array.forEach { print($0.name) }
You could use MirekE's solution which would work but here's an alternative solution.
First step would be identifying what the unique identifier on your FriendModel object is such as an id property.
Then on your model, since it is an NSObject, override the isEqual function like this:
override public func isEqual(object: AnyObject?) -> Bool {
let friend = object as? FriendModel
if self.id == friend?.id { return true }
return false
}
At this point you can use your desired form of iteration to find your element in the array and use remove.

Filtering arrays for use with UISearchBar

I have a table view which displays a user's Name, Company Name and Photo (PFFile). Each tableView row I have has all of this information in it.
I am using UISearchBarDelegate and IB to implement a search function to filter by the user's Name. It is finding the correct user but I have not been able to also update the company photo.
How do I filter the other arrays? The items I need from the arrays will be at the same index as the ones taken from the user's Name array.
EDIT: I am trying a different data structure and am receiving array index out of range, updated code below:
var filterArray = [User]() //<-- globally declared
var userArray = [User]() //< Global
class User {
var name: String?
var company: String?
init (name: String?, company: String?) {
self.name = name
self.company = company
}
}
//In a class which populates the search arrays
for object in unwrappedSucceeded {
let username = object.valueForKey("username") as! String
let companyName = object.valueForKey("companyName") as! String
let user = User(name: username, company: companyName)
userArray.append(user)
}
//tableViewController
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
filterArray.removeAll(keepCapacity: false)
if searchText.characters.count != 0 {
isSearch = true
self.search(searchText)
} else {
isSearch = false
}
}
func search(text: String) -> Void {
filterArray = userArray.filter({$0.name == text})
}
//In cellForRowAtIndexPath
cell.usernameCell.text = filterArray[indexPath.row].name //ARRAY INDEX OUT OF RANGE
Like I said you strongly recommend to group each user's info into one big container, therefore we could use array of struct or class, then it comes easier to filter.
schematic for the container:
struct Container
{
var username:String?
var companyName:String?
var photo:UIImage?
}
your main array will be : var arrayofData = [Container]()
Now when you are query your objects from parse, inside of your query function
// after you called the findObjectsWithBackgroundBlock()
// let's assume you check for error and if the [PFObject] is empty or not
for one in objectsFromParse
{
let photoToget = one["Photo"] as! PFFile
// next step should be to get the image data right :)
{
// let's assume that is the block when get the image data right:)
// check your data and assign it to some UIImage
// then
let userRepresentation = Container() //<-- we are creating a single object representation for each user
let username = one["username"] as! String //<--data we got from Parse
let companyName = one["companyName"] as! String
let userImage = //the UIImage which contains the data
userRepresentation.username = username
userRepresentation.companyName = companyName
userRepresentation.photo = userImage
// then we append
arrayOfData.append(userRepresentation)
}
}
Now we have all data into our array, so let's filter by username and also I hope you configure your tableView so when you have data from filter or regular array.
var filterArray = [Container]() //<-- globally declared
func search(text: String) -> Void
{
filterArray = arrayOfData.filter(){ (Container) -> Bool in
let range = Container.name!.rangeOfString(text, options:NSStringCompareOptions.CaseInsensitiveSearch) return range != nil }
// then you are good to go
}
let arr1 = [10,20,40]
let e1 = arr1.enumerate()
let arr2 = ["a","b","c"]
let f1 = e1.filter { $0.element % 20 == 0 }
let f2 = arr2.enumerate().filter { j, _ in
f1.contains { i, _ in
i == j
}
}
print(f1.map{$0.element}, f2.map{$0.element})
// [20, 40] ["b", "c"]
now you have both arrays "filtered". the best, what you can do is redesigning your data model!

Resources