Update UIlabel text with a String - arrays

I have a label in the prototype table view cell, and also a UITextviewfield, I want to update the text of the label by using UITextviewfield.
first I created a struct:
struct CellElements {
let title: UILabel
}
then an array:
var list = [CellElements] ()
then I use these codes to add the text inside the UITextfieldto the list array and later I will add them in the table view.
#IBOutlet weak var inputField: UITextField!
#IBAction func addName(_ sender: UIButton) {
list.append(inputField.text)
}
the problem is, swift doesn't let me to do that with this error
Cannot convert value of type 'String?' to expected argument type 'CellElements'
I will appreciate for your help in advance.

list is an array of CellElements. When you attempt to append to that array, you need to add a CellElements instance.
But your line:
list.append(inputField.text)
is attempting to append a String. Hence the error since String isn't CellElements.
What you want to do is to create an instance of CellElements from the text field and then append that instance.
list.append(CellElements(title: inputField.text!))
Note that you need a String and inputField.text is an optional String. This is a case where you can safely force-unwrap an optional. See the documentation for UITextField text for why this is safe.

Related

Displaying text from an array into text box

First off, I'd like to apologize for the newbie question, I'm trying to learn as I go with this. I've made a couple basic iOS apps but this is my first venture into macOS Storyboard apps with no formal training in programming.
I'm trying to create a program to help my partner (a writer by profession) with their creative blocks by displaying character, setting, and action attributes that can be used in a story. (Screenshots attached for a better representation)
I believe I have the basic window formatting down but I'm getting stuck on how to link the "Attribute" buttons to the text fields to display elements in the array. I just have placeholder elements until I get it working but ideally you would click the attribute button and it would display a random attribute from the array into the text box.
I've included what I was able to piece together so far but it's failing to build at the line to output to the text box and I can't seem to figure it out.
The error is:
Cannot assign value of type () to type String
Any assistance is appreciated!
import Cocoa
class SecondViewController: NSViewController {
#IBOutlet weak var CharAtt1: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
#IBAction func CharAttBut1(_ sender: NSButton) {
let array = ["Swift", "SwiftUI", "UIKit"]
let randomElement = array.randomElement()!
CharAtt1.stringValue = print("\(randomElement)")
}
}
Obviously, the offending line of code is:
CharAtt1.stringValue = print("\(randomElement)")
It's got a fair number of issues. The most prudent is that print has a type of (approximately, I'm simplifying) (Any) -> Void. You're calling it, passing it a string ("\(randomElement)"). This will print the string to the console, but it will also return back a () (a.k.a. the empty Tuple, of type Void). As the error message suggests, this can't be assigned to CharAtt1.stringValue, which is expecting a String.
The fix is simple, don't call print:
// If you do want to print it, do it in a separate expression
print("\(randomElement)")
CharAtt1.stringValue = "\(randomElement)"
But there's another issue: "\(randomElement)" is useless. randomElement is already a String. You could just write:
print(randomElement)
CharAtt1.stringValue = randomElement
I'd say that "\(anything)" is kind of anti-pattern. If you need to convert something to a string, I think it's better to do so in a way that's more explicit about the conversion you want. E.g. using String(anything) (if such an initializer exists), or String(describing: anything), or String(reflecting: anything) (depending on your usecase)

Swift: How do you use a variable in an array?

I am using a pod called iOSDropDown to display a dropdown selection menu for a textfield. I am getting a list of data from php to populate that selection menu that Im storing in a variable.
The PHP data passed stored in a swift variable looks like this when printed -> "option01","option02","option03"... and so on. This is dynamic data that will change that is why I am retrieving from PHP/MYSQL Database instead of just manually typing in the options in the Swift array.
Below is my code. What I am trying to do is use the "dropdownData" variable that holds the options for the array. Each option should be in its own row and separately selectable. What I am getting is one option, one string of coding with all my options as shown in the picture below.How would I use the dropdownData variable to display options instead of one string, one option?
dropdownData = "option01","option02","option03"... etc. ALL OPTIONS STORED IN THIS ONE ARRAY
let dropdownData : String = (dumpsArray[indexPath.row] as AnyObject).value(forKey: "dropdownData") as! String
.
cell.nameField.optionArray = [dropdownData]
Image
In the image above there should be no comma after styrofoam cooler... the next product should be the next option displaying under the styrofoam cooler and separately selectable.
Seems like dumpsArray[indexPath.row] as AnyObject).value(forKey: "dropdownData") returns a String where names are comma separated,
so
if let nameString = dumpsArray[indexPath.row] as AnyObject).value(forKey: "dropdownData") as? String {
let namesArray = nameString.components(separatedBy: ",")
cell.nameField.optionArray = namesArray
}
That should do

Displaying text from nested multi-dimensional ForEach in SwiftUI

I am fairly new to SwiftUI but am pulling my hair out trying to display text from two ForEach loops. I am working on a song app that would display lyrics in stanzas. My data is one array Lyrics that holds Verses which is another array. Each verse is a stanza. And each verse has a string array that stores the lyrics for one line.
//Lyrics variable
#Published var lyrics: [Verse]? = [Verse]()
//Verse structure storing each line
struct Verse: Codable, Identifiable {
let id = UUID()
let verseContent: [String]
}
The part I am having trouble is in implementation of getting all of the information into Text within my View. One ForEach loop works and I can get the first line of each of my stanzas as follows
//Builds Fine with this code
ForEach(lyrics) { verse in
Text(verse.verseContent[0])
}
But the problem is when I try and do a nested ForEach to get all of the lines in each stanza with the following.
return AnyView(
ForEach(lyrics) { verse in
ForEach(verse.verseContent { line in
Text(line)
)
}
)
When I try this I get the following error
Explicitly specify the generic arguments to fix this issue
Generic parameter 'ID' could not be inferred
Referencing initializer 'init(_:content:)' on 'ForEach' requires that 'String' conform to 'Identifiable'
Solved! It just needed .self for both of the ForEach statements

Get indexOfObject method without using Foundation objects

by selecting 1st tableView row/section I want to check if selected item already in 2nd tableView ?, if yes then find that selected item indexOfObject in 2nd tableView.
NSInteger sectionIndex = [[allSelectedProducts valueForKey:#"productID"] indexOfObject:[allProductData[indexPath.section] valueForKey:#"productID"]];
this will return the index of selected object in allSelectedProducts, Returns the lowest index whose corresponding array value is equal to a given object.
I want to perform this same task in swift, how can I achive that !
In Swift I've taken allSelectedProducts for 1st tableView and allProductData for 2nd tableView both arrays with Array<Dictionary<String, Any>> type
I want to perform this task without using Foundation classes, can we perform that same task in array using indexOf in Swift !?
let productIndex = allSelectedProducts.indexOf(<#T##predicate: ([String : Any]) throws -> Bool##([String : Any]) throws -> Bool#>)
If we can, then how ?
please guide me how to use indexOfin swift
thanx in advance for any help
Probably something like this:
let searchedProductID = allProductData[indexPath.section]["productID"]
let index = allSelectedProducts.indexOf { $0["productID"] == searchedProductID }
which is a direct translation of your original code

Correct Syntax for accessing this array

I have a View controller, with a tableview inside of it. I have a navigation button called "create". After the user has filled in a couple textfields and selected a cells from the UITableview i want the create button to create a parse object with the selected and inputed information.
I have these arrays..
var name = [String]()
var address = [String]()
var theseItems:[String] = [] //globalArray
im appending the selected cells to "theseItems" array.
//i have already queried and added what i wanted, to the name and address array..so they are filled with information.
didSelectRowAtIndexPath {
self.theseItems.append(name[indexPath.row] as String)
self.theseItems.append(address[indexPath.row] as String)
now with the create Button i want to create an object from this information but am having a hard time accessing the selected cell index path in the button...
#IBAction func createButton(sender: AnyObject) {
let thisObject = PFObject(className:"thisObject")
thisObject["name"] = name.text
thisObject["address"] = address.text
thisObject["selectedCell"] = theseItems(name[indexPath.row])
thisObject["selectedCell2"] = theseItems(address[indexPath.row])
//error** unresolved identifier "indexPath"
I'm not sure the correct way to access the array with a cells information.. to save it to parse. thanks in advance!
thisObject.saveEventually()
You can get the index paths of the currently selected cells by calling the indexPathsForSelectedRows() method on the table view (or indexPathForSelectedRow() if constrained to a single selection at one time).
You're trying to access a an array position from text, but text is a textField, not an array

Resources