ios - EXC_BAD_ACCESS UITable 在 numberOfRowsInSection 中设置 tableHeaderView

标签 ios swift uitableview exc-bad-access

我正在尝试在 numberOfRowsInSection 中设置 tableHeaderView。但是我得到 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,它就会在 self.bookmarkTableView.tableHeaderView = nil 行上有 EXC_BAD_ACCESS

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

我该如何解决这个问题?

最佳答案

您应该通过 UITableViewdataSource 提供 header :

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

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

关于ios - EXC_BAD_ACCESS UITable 在 numberOfRowsInSection 中设置 tableHeaderView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43991078/

相关文章:

javascript - 了解控制台错误 "TypeError: undefined is not an object"和 "Uncaught TypeError: Cannot read property ' 0' of undefined"

ios - 从 YouTube JSON 数据 Objective C 获取缩略图

ios - 在 iOS 中通过 opencv 或 opengl 拉伸(stretch)图像区域

swift - 带有 Swift 的 UICollectionViewCell 中的 UIScrollView

ios - CoreBluetooth用字节数组写入数据

ios - 在 Swift 中使用 ALAsset

ios - 为什么 TabBar 在 segue 之后隐藏?

iphone - 如何在tableview上实现循环滚动

ios - KIF测试时如何自动点击OK响应 "<app> would like to use your current location"?

ios - 你如何获得特定设备的当前位置?