Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

ios - Why UITableView Display Data Incorrectly

I have a list and trying to display it on UITableView alternating with empty UITableViewCell.

So it's like row 0 2 4 6 8 ... on TableView will be displaying list item 0,1,2,3,4 ...

Then row 1 3 5 7 9 ... will be empty.

After I fired it up, TableView show data of list in the correct manner, but the list below the screen was messed up when I scroll it down, they all cramped together without space. Then I scroll up to see the top rows which was displaying correctly, now also cramped up together.

So basically everything off-screen went wrong and behaved incorrectly when I brought them up on screen again.

Can someone explain why?

Code is pretty basic. The list of data.

var list:[listItem] = [
    ("WQGnNS4EOBrOlWpjCWee", 0),
    ("cC7Jt6xbY8652kzDncM9", 1),
    ("7Nvvb7VTs7E8WHbPvIKX", 2),
    ("DboaZXpetdzEIVv5mi7t", 3),
    ("xhHBPJwnG5fmnsD0EE4c", 4),
    ("I4OIxzEwuZJrkkgLaQEO", 5),
    ("WTITgSOoRCyl5J0s0qki", 6),
    ("HcBNjhp3cQsPjMYSJMSG", 7),
    ("lO3wIZbOAWDmyFwKAPJn", 8),
    ("AA1lw1LtCMI0dXV1GgV4", 9),
    ("uRMCOWZlypU21BsOxVwR", 10),
    ("gIIUZq9UWM0CvZ42n4R8", 11),
    ("K6tlnMuWyqnmrfbirWep", 0),
    ("Fooh0mQ7tdpvXi2UMTtT", 1),
    ("tHHMyYW6vis9ANO8SJaa", 1),
    ("vd5x8HCzpNu5NpmEJAPE", 2),
    ("ttOtZIAWsJPZvCYlSk3o", 1),
    ("PSbxlnVLlJONXJJhbCkw", 2),
    ("SGL4YtEomhD2p4D6q7sY", 3),
    ("ixaft55n1VHJmvImg0qm", 4),
    ("TGJ6h40TzL6smKd8DT9C", 5)]

DataSource

extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        list.count*2-1;
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "default", for: indexPath)
    
        if indexPath.row % 2 == 0 {
            cell.textLabel?.text = list[indexPath.row/2].0
        }
        else {
            // cell.textLabel?.text = ""
        }
        return cell
    }
}

The second-to-last line is commented out. If I uncomment it, then everything will work just fine.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can simple use ternary Operator like below in a single line of code:

 cell.textLabel?.text = indexPath.row % 2 == 0 ? list[indexPath.row].0 : ""

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...