dequeueReusableCell不清除单元格上的旧视图

时间:2017-11-19 01:58:17

标签: ios swift uitableview

我现在有一个表格视图,它设置为像Netflix或Spotify侧滚动视图一样工作。为此,我为每个单独的表格单元格添加了一个滚动视图,该单元格保存了列表中每个项目的子视图。

我遇到的问题是表格视图不是从旧单元格中清除滚动视图,所以一旦我向下滚动一下,旧滚动视图就会开始出现在新单元格后面。

我认为这与dequeueReusableCell的工作方式有关,所以这里是我认为相关的代码

TableViewCell:

class MenuItemsScrollCell: UITableViewCell {
    @IBOutlet weak var scrollView: UIScrollView!

    func setup(for scrollItems: [ScrollItemView]) {
        let sideScroll = SideScroll(scrollItems: scrollItems, scrollView: scrollView)
        sideScroll.build()
    }
}

SideScroll - 负责设置scrollview并向其添加单个视图对象的类

class SideScroll: NSObject {
    var scrollItems: [UIView]!
    weak var scrollView: UIScrollView!
}

extension SideScroll {
    convenience init(scrollItems: [UIView], scrollView: UIScrollView) {
        self.init()
        self.scrollItems = scrollItems
        self.scrollView = scrollView
    }
    func build(){
        for (index, scrollItem) in scrollItems.enumerated() {
            setSizeOf(scrollItem)
            setPositionFor(scrollItem, at: index)
            scrollView.addSubview(scrollItem)
        }
        setContentSize(for: scrollView)
        // setSizeOf(:scrollItem), setPositionFor(:scrollItem,at:index) and setContentSize(for:scrollView) all do exactly what you would expect them to.
    }
 } 

然后我的方法单元格(实际上不是cellForRowAt因为我使用了稍微复杂的模式,但是它做了同样的事情,我不认为问题来自那个模式所以我赢了&# 39; t发布代码。)

func cell(for row: Int, in tableView: UITableView) -> UITableViewCell {
    guard let menuItemsScrollCell = tableView.dequeueReusableCell(withIdentifier: "MenuItemsScrollCell") as? MenuItemsScrollCell else {
        fatalError("Was expecting MenuItemsScrollCell. Got Something Else." )
    }
    let menuItems = self.menuItems(at: row) // Returns an array of menu item model objects that correlates to one row of the table.
    let scrollItemViews = populateScrollItemViews(for: menuItems)
    menuItemsScrollCell.setup(for: scrollItemViews) // Method from first code sample
    return menuItemsScrollCell
}

func populateScrollItemViews(for menuItems: [MenuItem]) -> [ScrollItemView] {
    var output = [ScrollItemView]()
    for menuItem in menuItems {
        guard let scrollItemView = Bundle.main.loadNibNamed("ScrollItemView", owner: nil, options: nil)![0] as? ScrollItemView else {
            fatalError()
        }
        scrollItemView.titleLabel.text = menuItem.title
    }
    return output
}

1 个答案:

答案 0 :(得分:1)

重复使用表格视图单元格。您需要清除prepareForReuse()中的旧状态。

class MenuItemsScrollCell: UITableViewCell {
    @IBOutlet weak var scrollView: UIScrollView!

    func setup(for scrollItems: [ScrollItemView]) {
        let sideScroll = SideScroll(scrollItems: scrollItems, scrollView: scrollView)
        sideScroll.build()
    }

    override func prepareForReuse() {
        super.prepareForReuse()
        for subview in scrollView.subviews {
            subview.removeFromSuperview()
        }
    }
}