首页 > 解决方案 > IOS UITableView display first 5 rows of an array

问题描述

I have a UITableView with 1 cell and when the array loads I just want for the user to see the content of the first 5 rows and blur the rest. So, if there is an array with 20 items, the first 5 need to be visible and the remaining 15 with a blur. With the code below, I'm able to just add a blur to row 5 only, I can't figure this out. Any help is greatly appreciated.

ViewController

let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .light))



    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return array.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomTableViewCell
        cell.cellLbl?.text = array[indexPath.row]

        if indexPath.row == 5 {
            visualEffectView.frame = cell.bounds
            visualEffectView.layer.masksToBounds = true
            cell.addSubview(visualEffectView)
        }
        return cell
    } 

enter image description here

标签: iosswiftuitableviewcellblur

解决方案


You can't share a single visual effect view which you move between cells. (A view can only exist once in thew view hierarchy. If you add it as a subview in 2 places, it gets removed from the first place).

Your code should also use if indexPath.row >= 5, not if indexPath.row == 5

I would suggest creating a custom subclass of UICollectionViewCell that has a public blurView IBOutlet. Install a blur view in the cell in your XIB/storyboard. In your tableView(_:cellForRowAt:) method, hide the blur view if the row is < 5, else un-hide it.


推荐阅读