How do I proceed on populating the UITableView [closed] - ios

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I got these item properties and I need to populate the UI by setting the name on each UITableViewCell, each cell has the following properties:
Name
Description
Photo
Old Price
New Price
However, I don't know how I should proceed. Could you guys take a look and give me a hand, please?
Printed Item names:
HTML e CSS
Sistema de Banco de Dados
Programação com Arduino
Segredos do Hacker Ético
Google Android
Android Essencial
Desenvolvimento de Jogos Para Android
iOS: Programe para iPhone e iPad
A Guerra dos tronos
Crepusculo
ViewController:
import UIKit
class TelaCategorias: UIViewController, UITableViewDataSource, UITableViewDelegate {
//Class Instanciated
var item:[CategoriaIDItems]?
override func viewDidLoad() {
super.viewDidLoad()
for item in item!{
print(item.nome)
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (item?.count)!
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableIDCategorias", for: indexPath) as! TelaCategoriasCell
cell.textLabel?.text = ?????
return cell
}
}

Append the item names to an array
In cellForRowAt indexPath:
cell.textLabel.text = yourArrayName[indexPath.row]

So you need to read up on setting up a data source for a table view.
Before you tackle YOUR table view, you might want to go through a Swift/iOS tutorial on table views and follow that so you get the gist of it.
Suggestion: Don't use the name "item" (singular) for your array. Use the name "items" plural. An item is a thing. Items is more than one thing.
Now define a struct that has fields for the properties that you want to display in your table view.
Make items be an array of those structs.
Write your tableView(_:cellForRowAt:) method so it fetches an item from the items array and uses that item to set the fields in your table view cell.
If you don't understand any of these steps you will need to do some study and read up on how to do this. Expect it to take a couple of days to sort this out. It's confusing the first time you tackle it, but you need to go through the exercise.

Related

UISlider issue in ios 16.3.1 [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 days ago.
Improve this question
I was implementing multiple sliders in a page in ios 14.2. The UI had a tableview and 4 cells. Each cells had a slider. It was working fine in 14.2. But when I updated my iPhone os to 16.3.1, the sliders are not behaving properly.
When I try to move the first slider, the first and fourth slider is moving at the same time. And when second slider is moved, second and third sliders are getting moved. Have anyone encountered with this issue before.
You might be reloading/updating you tableView when slider changes. Do not reload table view.
Create a Model class for you cell
class MyModel {
var title:String?
var sliderValue:CGFloat
}
Pass the model to cell and update you model directly
class MyCustomCell:UITableViewCell{
var model:MyModel!
func configure(item:MyModel) {
self.model = item
}
#IBAction func sliderChanges(_ sender: UiSlider) {
self.model.sliderValue = sender.value
}
}
And finally pass the change your cell for indexPath method
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCustomCell", for:indexPath) as? MyCustomCell
cell.configure(item:self.items[indexPath.row])
return cell
}

How to parse this type of json and set in UITableView cell [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How to set this json in a tableView.
{
"page":0,
"pageSize":5,
"totalPageCount":16,
"wkda":{
"020":"Abarth",
"040":"Alfa Romeo",
"042":"Alpina",
"043":"Alpine",
"057":"Aston Martin"
}
}
Create a struct which represents your data
struct YourObjectName: Codable {
let page, pageSize, totalPageCount: Int
let wkda: [String: String]
}
When getting your data from the server, parse your json into your newly created object, and store that object somewhere in your viewController.
let yourObject = try? newJSONDecoder().decode(YourObjectName.self, from: jsonData)
When configuring the tableView, set the number of rows based on your data:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return yourObject.count // Or something similar, based on your needs
}
Finally use your data to populate the cells:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SomeIdentifier", for: indexPath)
// Populate your cell
return cell
}
Also I encourage you to read a bit about TableView. Here is a good source to start: TableViews

How to write function / code to switch between two text ? Language learning app. So Language 1 to Language 2 [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I made an app for learning Japanese language.
So When we click on the button it will change the label.text = "English" to Label.text = "Japanese" I use the if function as below.
#IBAction func datingButtonPressed1(_ sender: UIButton) {
if datingLabel01.text == "Anata ga suki desu.
- あなた が すき です" {
datingLabel01.text = "I like you."
}else {
datingLabel01.text = "Anata ga suki desu. - あなた が すき です"
}
I have 15 words and phrases for each categories so I already had to create 150 IB Actions and labels and so .
picture below.
enter image description here
Now my question is :
What is the better way to do this ?
The app link is :
https://apps.apple.com/ca/app/learn-japanese/id1528287144
You need to structure your translations in some kind of data model. A sample approach could look like this :
class Translation {
private let en: String
private let jp: String
var isEnglishDisplayed = true
var currentText: String {
return isEnglishDisplayed ? en : jp
}
init(en: String, jp: String) {
self.en = en
self.jp = jp
}
}
And then you can have some kind of factory creating lists of these objects :
class TranslationCategories {
// Returns an array of `Translation` objects for `General` category
static func getGeneralCategory() -> [Translation] {
return [
Translation(en: "Translation", jp: "翻訳 - Hon'yaku"),
// Other elements of category
]
}
}
Then, in your view controller, you can get rid of all the IBActions for each of the cells, and use UITableViewDelegate and UITableViewDataSource methods to set your data, something similar to this :
privat evar translations: [Translation] = []
override func viewDidLoad() {
super.viewDidLoad()
self.translations = TranslationCategoriews.getGeneralCategory()
}
func numberOfSections(in: UITableView) -> Int {
return 1
}
func tableView(_ : UITableView, numberOfRowsInSection: Int) -> Int {
return translations.count
}
func tableView(_ : UITableView, cellForRowAt: IndexPath) -> UITableViewCell {
// dequeue cell as needed
cell.text = self.translations[indexPath.row].currentText
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let translation = translations[indePath.row]
translation.isEnglishDisplayed.toggle()
let cell = tableView.cellForRow(at: indexPath)
cell.text = translation.currentText
}
This is heavily simplified, just to show the general idea of the approach. You may need to adjust it more or less, depending on the current state of your code as a whole.
Things not covered by this sample :
Figuring out how to choose which category to get from TranslationCategories based on which one user selected
Figuring out how to use the buttons, instead of selecting entire cell
These are left as an excercise to the reader since they depend more on the entire approach.
To sum up :
You need some form of data model that will enable you to structure your data
You need to adjust your view controller to make use of this structured data, instead of using static texts and dedicated methods for each row
This of course is not the "only" way or "the best" way. Its just a proposition on how to solve the issue presented in the question.

Control "Program Flow" in Table View

again me with a short question since Swift is confusing me ATM - but I hope I will get used to it soon ;)
Ok so what I was wondering is: When I call a TableView and generate different Cells is there a way to Interrupt after a few and wait for User Input and react to it?
For Example: 2nd Cell is something like "Go to North or West" after that I want a User Input - with Buttons - in whatever direction he likes to go and react to it with following Cells (different Story Parts -> out of other Arrays?).
What is confusing me is that I just load the whole Application in viewDidLoad and i don't know how I can control the "Flow" within this.
I would really appreciate if someone could show me how I can achieve this maybe even with a small description about how I can control the Program Flow within the Method. I really think this knowledge and understanding would lift my understanding for Swift a few Levels higher.
Thanks in advance!
Here is my current Code which is not including any functionality for the named Question since I don't know how to manage this :)
import UIKit
class ViewController: UIViewController {
var storyLines = ["Test Cell 1 and so on first cell of many","second cell Go to North or West","third Cell - Buttons?"]
var actualTables = 1
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.dataSource = self
}
#IBOutlet weak var tableView: UITableView!
}
extension ViewController : UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return storyLines.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TxtLine", for: indexPath)
cell.textLabel?.text = storyLines[indexPath.row]
cell.textLabel?.numberOfLines = 0;
cell.textLabel?.lineBreakMode = .byWordWrapping
return cell
}
}
Cocoa is event driven. You are always just waiting for user input. It's a matter of implementing the methods that Cocoa has configured to tell you about it.
So here, for example, if you want to hear about when the user presses a button, you configure the button with an action-and-target to call a method in your view controller when the user presses it. That way, your method can see which button the user pressed and remake the table view's data model (your storyLines array) and reload the table with the new data.

Find out UITableViewCells with detailTextLabel [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'd like to find out all UITableViewCells (number varies) which have an detailTextLabel with the text "Done" in it. How can I do this in Swift?
You should not do this. Neither in Swift nor in any other language. You should query the dataSource because that is where the true state is stored. If you scroll a cell offscreen it get's reused, and the text gets set to something else. You can't rely on that information. Even worse, if you rely on texts in your cell you never get the whole picture about your dataSource, because the cells that are offscreen simply don't exist.
Here's what you should do: Somewhere in your code you set the text to "Done" depending on the state of an object. Use the same decision to find all objects that are done.
For example, if your object has an isDone getter, you hopefully use something like this to create the cell:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ProjectCell", forIndexPath: indexPath) as ProjectCell
let project = allProjects[indexPath.row]
if project.isDone {
cell.detailTextLabel?.text = "Done"
}
else {
cell.detailTextLabel?.text = nil
}
return cell
}
as you can see you decide depending on isDone if the "Done" text will be displayed.
So you can create a function that uses the same test to create an array that contains only projects that are done.
func projectsThatAreDone(allProjects: [Project]) -> [Project] {
let matchingProjects = allProjects.filter {
return $0.isDone
}
return matchingProjects
}
and you then use let doneProjects = projectsThatAreDone(allProjects)

Resources