Swift UITableViewCell显示默认隐藏的数据

时间:2015-05-29 08:22:33

标签: ios uitableview swift

我有一个看似随机的问题,我的UITableView中的某些单元格显示的数据默认为隐藏。

解释隐藏数据。

它是一个股票投资组合,您可以点击一个单元格来扩展它(并查看此数据)。当它关闭时,数据再次被隐藏。

这是我面临的问题的屏幕截图,默认情况下会导致随机单元显示此数据。

enter image description here

在上面的屏幕截图中," RUS.TO"和" CUB"显示隐藏数据的单元格。

以下是如何设置隐藏的视图和标签:

// #Advanced data

    stockNameView.setTranslatesAutoresizingMaskIntoConstraints(false)
    stockNameView.hidden = true
    self.addSubview(stockNameView)

    purchasePriceView.setTranslatesAutoresizingMaskIntoConstraints(false)
    purchasePriceView.hidden = true
    self.addSubview(purchasePriceView)

    lastPriceView.setTranslatesAutoresizingMaskIntoConstraints(false)
    lastPriceView.hidden = true
    self.addSubview(lastPriceView)

    daysHeldView.setTranslatesAutoresizingMaskIntoConstraints(false)
    daysHeldView.hidden = true
    self.addSubview(daysHeldView)

重叠的8个标签是上述4个视图的子视图。

正如您所看到的,这些视图默认设置为隐藏。所以我不认为问题在于我的细胞类?

我的代码中只有一个位置,我将这4个UIViews的隐藏值设置为false。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("com.Stocks.portfolioCell", forIndexPath: indexPath) as! portfolioCell


    if indexPath.row % 2 == 0 {
        cell.backgroundColor = UIColor.whiteColor()
    } else {
        cell.backgroundColor = UIColor.formulaWhiteColor()
    }

    if selectedCellIndexPath == indexPath {
        cell.tickerLabel.textColor = UIColor.formulaBlueColor()
        cell.heightSeperator.hidden = false
        cell.stockNameView.hidden = false
        cell.purchasePriceView.hidden = false
        cell.lastPriceView.hidden = false
        cell.daysHeldView.hidden = false
        cell.endSeperator.hidden = false
        tableHeight.constant = tableHeight.constant+250
        self.scrollView.contentSize = CGSize(width:self.view.bounds.width, height: self.contentView.frame.height)
    }

    if lastCollapsing == true || currentCollapsing == true {
        cell.tickerLabel.textColor = UIColor.formulaDarkGrayColor()
        cell.heightSeperator.hidden = true
        cell.stockNameView.hidden = true
        cell.purchasePriceView.hidden = true
        cell.lastPriceView.hidden = true
        cell.daysHeldView.hidden = true
        cell.endSeperator.hidden = true
        lastCollapsing = false
        currentCollapsing = false
        tableHeight.constant = tableHeight.constant-250
        self.scrollView.contentSize = CGSize(width:self.view.bounds.width, height: self.contentView.frame.height)
    }

    if stocks.count > 0 {
        let formulaStock = stocks[indexPath.row]

        ticker = formulaStock.valueForKey("ticker") as! String!

        let fontAwesomeBlueAttribute = [NSForegroundColorAttributeName: UIColor.formulaBlueColor(), NSFontAttributeName: UIFont(name: "FontAwesome", size: 12)!]
        let fontAwesomeGreenAttribute = [NSForegroundColorAttributeName: UIColor.formulaGreenColor(), NSFontAttributeName: UIFont(name: "FontAwesome", size: 12)!]
        let latoBoldDarkGrayAttribute = [NSForegroundColorAttributeName: UIColor.formulaDarkGrayColor(), NSFontAttributeName: UIFont(name: "Lato-Bold", size: 12)!]
        if ticker != "CASH" {
            let tickerString = "  \(ticker)" as NSString
            var tickerAttributedString = NSMutableAttributedString(string: tickerString as String)
            tickerAttributedString.addAttributes(fontAwesomeBlueAttribute, range: tickerString.rangeOfString(""))
            tickerAttributedString.addAttributes(latoBoldDarkGrayAttribute, range: tickerString.rangeOfString("  \(ticker)"))
            cell.tickerLabel.attributedText = tickerAttributedString
        } else {
            let tickerString = "  \(ticker)" as NSString
            var tickerAttributedString = NSMutableAttributedString(string: tickerString as String)
            tickerAttributedString.addAttributes(fontAwesomeGreenAttribute, range: tickerString.rangeOfString(""))
            tickerAttributedString.addAttributes(latoBoldDarkGrayAttribute, range: tickerString.rangeOfString("  \(ticker)"))
            cell.tickerLabel.attributedText = tickerAttributedString
        }

        weight = formulaStock.valueForKey("weight") as! Float
        cell.weightLabel.text = "\(weight.roundTo(2))%"

        cell.filledWeightWidth.constant = CGFloat(weight/2)

        lastPrice = formulaStock.valueForKey("lastPrice") as! Float
        purchasePrice  = formulaStock.valueForKey("purchasePrice") as! Float
        percentDifference = ((lastPrice/purchasePrice)*100.00)-100


        if ticker == "CASH" {
            cell.changeLabel.text = ""
        } else if percentDifference > 0 {
            cell.changeLabel.text = ("+\(percentDifference.roundTo(2))%")
            cell.changeLabel.textColor = UIColor.formulaGreenColor()
        } else if percentDifference < 0 && percentDifference > -100 {
            cell.changeLabel.text = ("\(percentDifference.roundTo(2))%")
            cell.changeLabel.textColor = UIColor.formulaRedColor()
        } else if percentDifference == 0 {
            cell.changeLabel.text = ("\(percentDifference.roundTo(2))%")
            cell.changeLabel.textColor = UIColor.formulaGreenColor()
        } else {
            cell.changeLabel.text = "N/A"
            cell.changeLabel.textColor = UIColor.formulaDarkGrayColor()
        }

        cell.stockNameLabel.text = formulaStock.valueForKey("name") as! String!
        cell.purchasePriceLabel.text = "$\(purchasePrice)"
        cell.lastPriceLabel.text = "$\(lastPrice)"
        daysHeld = formulaStock.valueForKey("daysHeld") as! Int
        cell.daysHeldLabel.text = "\(daysHeld)"
    }

    cell.selectionStyle = UITableViewCellSelectionStyle.None
    return cell
}

但是将单元格的隐藏值设置为false的代码部分。要求我的selectedCellIndexPath等于cellForRowAtIndexPath正在经历的当前indexPath。

我在这里设置了selectedCellIndexPath

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let cell = tableView.dequeueReusableCellWithIdentifier("com.Stocks.portfolioCell", forIndexPath: indexPath) as! portfolioCell
    if let selectedCellIndexPath = selectedCellIndexPath {
        if selectedCellIndexPath == indexPath {
            self.selectedCellIndexPath = nil
            currentCollapsing = true
            tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
        } else {
            lastCollapsing = true
            self.selectedCellIndexPath = indexPath
            tableView.reloadRowsAtIndexPaths([lastIndexPath], withRowAnimation: .None)
            tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
            self.lastIndexPath = indexPath
        }
    } else {
        selectedCellIndexPath = indexPath
        self.lastIndexPath = indexPath
        tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)
    }
    tableView.beginUpdates()
    tableView.endUpdates()
}

当我点击一个单元格时,它应该只是任何东西。

每次我为UITableView提供一组新数据时,我也要确保运行以下代码行:

(menuTabBarController.viewControllers as! [Portfolio_ViewController])[1].selectedCellIndexPath = nil

selectedCellIndexPath设置为nil,以避免任何潜在问题。

那么,为什么一些随机单元格会显示默认隐藏的信息?

当我测试这个错误时,我没有点击任何细胞。因此,selectedCellIndex此时甚至不应该有一个值。

4 个答案:

答案 0 :(得分:2)

很可能是由细胞重用引起的 - 如果之前选择的细胞被用作未选择的细胞,则其子视图的hidden值不会改变。

您可以通过添加else分支来解决此问题:

if selectedCellIndexPath == indexPath {
    ...
} else {
    // reset cell to non-selected state
    ...
}

答案 1 :(得分:1)

当您重复使用单元格时,旧值仍然存在,因此每次使用dequeueReusableCellWithIdentifier时,您都需要重置默认值或仍在其中缓存的最后值。

From apple documentation:

  

表视图的数据源实现   tableView:cellForRowAtIndexPath:应始终重置所有内容   重用一个单元格。

答案 2 :(得分:0)

function clkHandle(t) { $(this).siblings().find('audio').each(function(){ this.pause(); } t.firstChild.paused ? t.firstChild.play() : t.firstChild.pause(); } function dblclkHandle(t) { t.firstChild.currentTime = 0; } 获取单元格后,执行此操作。从视图中清除垃圾数据的负载,它也可以提供更好的性能。

dequeueReusableCell

答案 3 :(得分:0)

正如@chedabob在评论中提到的那样。 UITableViewCell将在重用单元格之前调用def init_driver(): driver = webdriver.Chrome("/Users/alexeynikitin/Desktop/chromedriver") driver.wait = WebDriverWait(driver, 5) return driver def findelem(driver, query): driver.get("https://www.yandex.ru/") try: box = driver.wait.until(ec.presence_of_element_located( (By.ID, "text"))) button = driver.wait.until(ec.visibility_of_element_located( (By.CLASS_NAME, "search2__button"))) box.send_keys(query) suggestion_box = driver.wait.until(ec.presence_of_element_located((By.CSS_SELECTOR, "body > div.i-bem.popup.suggest2.suggest2_theme_flat.suggest2_size_m.suggest2_adaptive_yes.suggest2_type_advanced.suggest2_ahead_yes.popup_adaptive_yes.popup_animate_no.popup_autoclosable_yes.popup_theme_ffffff.suggest2-detect_js_inited.suggest2_js_inited.popup_js_inited.popup_to_bottom.popup_visibility_visible"))) try: button.click() except ElementNotVisibleException: button = driver.wait.until(ec.visibility_of_element_located( (By.CLASS_NAME, "search2__button"))) except TimeoutException: print("ничего не нашел на https://www.yandex.ru/") if __name__ == "__main__": driver = init_driver() findelem(driver, "Тензор") time.sleep(10) driver.quit() 。重置您的观点和价值。因此,在tableviewcell类中覆盖方法prepareForReuse()

prepareForReuse()