Array for UITableView

It sounds easy and from the textbooks it looks very easy.

I carefully followed the textbooks from their words and still cannot get an array to display in my UITableView.

Here is my code.

- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. salesArray = [[NSMutableArray alloc] init]; //Add items [salesArray addObject:@"Credit"]; [salesArray addObject:@"Debit"]; [salesArray addObject:@"EBT"]; //Set the title self.navigationItem.title = @"Sale Type's"; } -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {return [salesArray count];} -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if(cell == nil) { cell = [[[UITableViewCell alloc]initWithFrame:CGRectZero reuseIdentifier:CellIdentifier]autorelease]; } NSString *value = [salesArray objectAtIndex:indexPath.row]; cell.textLabel.text = value; return cell; } 

And yes, I declared this in the .h file and the .m file.
Any help in any direction would be great, thanks!

+4
source share
4 answers

Declare your salesArray as your property, and in cellForRowAtIndexPath use

 cell.textLabel.text = [self.salesArray objectAtIndex:indexPath.row]; 
+8
source

I assume your view controller extends the UITableViewController? If so, you just need to add this line at the end of the viewDidLoad and / or viewDidAppear methods:

 [self.tableView reloadData]; 

Also, I would use self.salesArray instead of salesArray. It’s not entirely accurate what the difference is, but I have had problems in the past that did not add β€œI” to some of my variables.

+1
source

Your code looks fine, but I think you forgot to change the number of partitions from zero to one.

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } 
+1
source

In my point of view, this is much better and easy to understand according to the code below:

 import Foundation import UIKit class testTableViewController: UITableViewController { override func viewDidLoad{ super.viewDidLoad() } let nameList = ["name1","name2","name3","name4","name5","name6"] override func tableView(tableView: UITableView, numberOfRowsInSection section: Int)-> Int{ return nameList.count } override func tableView(TableView:UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ let cell = tableView.dequeueReusableCellWithIdentifier("test_row", forIndexPath: indexPath) let row1 = nameList[indexPath.row] cell.textLabel? .text = row1 return cell } } 
0
source

Source: https://habr.com/ru/post/1369535/


All Articles