Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.5k 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 Reply

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 : ""

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...