I’m totally new to IOS dev and I’m looking for help on what I’m sure is a simple issue. I’m building a test app to learn loops, code, IBoutlets etc and I have create an app that reads in between 1-5 random names into an array, I now want to read those elements into a table that I have on the same screen. If I try and use a WHILE loop then I get an error that it cannot find Return Cell, if I don’t use a loop then it prints all elements in every cell.
thanks
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
Table.dataSource=self
}
@IBAction func Buttonpressed (){
GetMoves()
}
func GetMoves() {
var i=0
var ArrayMove:String
ChosenNumber=Int(Field.text!)
ArrayMove=" "
while i < ChosenNumber{
ArrayMove=Moves[i]
ChosenMoves.append(ArrayMove)
i+=1
self.Table.reloadData()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ChosenMoves.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var movestring=" "
var i=0
// while i<ChosenMoves.count{
let Cell=Table.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomTableViewCell
i=indexPath.row
movestring=" "
movestring=ChosenMoves[i]
Cell.CellLabel.text=movestring
i+=1
return Cell
}
I want each array element appears on an individual row in the table.
2
Answers
As you a new to iOS dev please conform to the naming convention that methods and variables start with a lowercase letter. And whitespaces before and after equal signs increase the readability.
The method
cellForRowAt
is always called once for each index path. Get the item in the data source array by that index path. And use always thetableView
parameter in the method rather than accessing the IBOutlet directly.Side note: Never call
reloadData()
multiple times inside a loop. Call it once after the loopI think you are doing mistake while dequeuing cell. You have used
Table
where as you need to usetableView
. I think there is no need of declaring variablei
and similarly no need to increment it. Here is the updated method .I removed extra variables. One more point, above method by default gets called on every count. You don’t need to use loop for it.