草庐IT

ios - Swift UITableViewCell 显示默认隐藏的数据

coder 2023-09-09 原文

我有一个看似随机的问题,我的 UITableView 中的一些单元格显示了默认情况下应该隐藏的数据。

解释隐藏的数据。

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

这是我遇到的导致随机单元格默认显示此数据的问题的屏幕截图。

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

下面是应该隐藏的 View 和标签的设置方式:

// #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 个 View 的 subview 。

如您所见,这 4 个 View 默认设置为隐藏。所以我认为问题不在于我的单元格类?

我的代码中只有一处将这 4 个 UIView 的隐藏值设置为 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
}

但是将单元格的隐藏值设置为假的代码部分。要求我的 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 此时甚至不应该有值。

最佳答案

这很可能是由单元格重用引起的 - 如果以前选择的单元格用作未选择的单元格,则其 subview 的隐藏值不会改变。

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

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

关于ios - Swift UITableViewCell 显示默认隐藏的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30524662/

有关ios - Swift UITableViewCell 显示默认隐藏的数据的更多相关文章

  1. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  2. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  3. ruby - 默认情况下使选项为 false - 2

    这是在Ruby中设置默认值的常用方法:classQuietByDefaultdefinitialize(opts={})@verbose=opts[:verbose]endend这是一个容易落入的陷阱:classVerboseNoMatterWhatdefinitialize(opts={})@verbose=opts[:verbose]||trueendend正确的做法是:classVerboseByDefaultdefinitialize(opts={})@verbose=opts.include?(:verbose)?opts[:verbose]:trueendend编写Verb

  4. ruby-on-rails - 使用 Sublime Text 3 突出显示 HTML 背景语法中的 ERB? - 2

    所以我在关注Railscast,我注意到在html.erb文件中,ruby代码有一个微弱的背景高亮效果,以区别于其他代码HTML文档。我知道Ryan使用TextMate。我正在使用SublimeText3。我怎样才能达到同样的效果?谢谢! 最佳答案 为SublimeText安装ERB包。假设您安装了SublimeText包管理器*,只需点击cmd+shift+P即可获得命令菜单,然后键入installpackage并选择PackageControl:InstallPackage获取包管理器菜单。在该菜单中,键入ERB并在看到包时选择

  5. ruby-on-rails - date_field_tag,如何设置默认日期? [ rails 上的 ruby ] - 2

    我想设置一个默认日期,例如实际日期,我该如何设置?还有如何在组合框中设置默认值顺便问一下,date_field_tag和date_field之间有什么区别? 最佳答案 试试这个:将默认日期作为第二个参数传递。youcorrectlysetthedefaultvalueofcomboboxasshowninyourquestion. 关于ruby-on-rails-date_field_tag,如何设置默认日期?[rails上的ruby],我们在StackOverflow上找到一个类似的问

  6. ruby-on-rails - 在默认方法参数中使用 .reverse_merge 或 .merge - 2

    两者都可以defsetup(options={})options.reverse_merge:size=>25,:velocity=>10end和defsetup(options={}){:size=>25,:velocity=>10}.merge(options)end在方法的参数中分配默认值。问题是:哪个更好?您更愿意使用哪一个?在性能、代码可读性或其他方面有什么不同吗?编辑:我无意中添加了bang(!)...并不是要询问nobang方法与bang方法之间的区别 最佳答案 我倾向于使用reverse_merge方法:option

  7. ruby-on-rails - link_to 不显示任何 rails - 2

    我试图在索引页中创建一个超链接,但它没有显示,也没有给出任何错误。这是我的index.html.erb代码。ListingarticlesTitleTextssss我检查了我的路线,我认为它们也没有问题。PrefixVerbURIPatternController#Actionwelcome_indexGET/welcome/index(.:format)welcome#indexarticlesGET/articles(.:format)articles#indexPOST/articles(.:format)articles#createnew_articleGET/article

  8. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

  9. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  10. ruby - Ruby 有 `Pair` 数据类型吗? - 2

    有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳

随机推荐