【问题标题】:EXC_BAD_ACCESS UITable set tableHeaderView in numberOfRowsInSectionEXC_BAD_ACCESS UITable 在 numberOfRowsInSection 中设置 tableHeaderView
【发布时间】:2017-05-16 01:19:08
【问题描述】:

我正在尝试将tableHeaderView 设置为numberOfRowsInSection。但我收到EXC_BAD_ACCESS,输出控制台中没有任何消息。

下面是我的numberOfRowsInSection 函数。

// number of rows in table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    //SECTION 1
    if self.titles.count == 0 {
        self.noBookmarkView.alpha = 1.0
    }
    else {
        self.noBookmarkView.alpha = 0.0
    }
    //=====================================

    //SECTION 2
    if self.idsb.count != self.ids.count {
        self.bookmarkTableView.tableHeaderView = self.filteredView
    }
    else {
        self.bookmarkTableView.tableHeaderView = nil
    }
    //=====================================

    return self.titles.count
}

下面是我的viewDidLoad,我在其中初始化filteredView

@IBOutlet weak var noBookmarkView: UIView!
var filteredView: UIView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    filteredView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: bookmarkTableView.frame.width, height: 25))
    filteredView.backgroundColor = UIColor.init(red: 0.4, green: 0.4, blue: 0.71, alpha: 1.0)
    let label: UILabel = UILabel.init(frame: filteredView.frame)
    label.text = "Filtered"
    label.font = UIFont.init(name: "System", size: 14.0)
    label.adjustsFontSizeToFitWidth = true
    filteredView.addSubview(label)
}

所以在我添加 filteredView 之前,它与 noBookmarkView 完美配合。

现在它在self.noBookmarkView.alpha = 0.0 上有错误EXC_BAD_ACCESS。如果我注释掉 SECTION 2 它可以正常工作。如果我将SECTION 1 注释掉,那么EXC_BAD_ACCESS 就在self.bookmarkTableView.tableHeaderView = nil 线上。

我不明白为什么它会在 self.noBookmarkView.alpha = 0.0 上失败,而看起来 SECTION 2 是导致问题的原因。

我该如何解决这个问题?

【问题讨论】:

  • 我看不到问题,但我想知道noBookmarkView 是否被声明为弱是问题所在。还有什么会引用该视图,并且可能会被释放和归零?
  • @GaryMakin 我把它改成@IBOutlet var noBookmarkView: UIView! 还是有同样的问题。
  • 这是我唯一的猜测,抱歉。
  • @GaryMakin 这一切都很好。谢谢!希望有人能弄清楚。
  • 您是否尝试过清理和重建?有时只需要清洁,一切正常

标签: ios swift uitableview exc-bad-access


【解决方案1】:

您应该通过UITableViewdataSource 提供标头:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    return self.filteredView
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 25
}

【讨论】:

  • 太棒了!那行得通。我注释掉了第 2 节并添加了该代码。我怎样才能使它只在self.idsb.count != self.ids.count时显示标题?
  • 你可以签入viewForHeaderInSection,如果你不想显示标题则返回nil。您可能还需要在 heightForHeaderInSection 中返回 height = 0
  • 完美!非常感谢!!
猜你喜欢
  • 1970-01-01
  • 2012-12-22
  • 2018-05-29
  • 1970-01-01
  • 2016-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多