2017-05-16 39 views
1

我試圖在numberOfRowsInSection中設置tableHeaderView。但是我得到了EXC_BAD_ACCESS,在輸出控制檯中沒有消息。EXC_BAD_ACCESS UITable set tableHeaderView inOfRowsInSection

以下是我的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是什麼原因導致的問題。

我該如何解決這個問題?

+0

我看不出問題,但我不知道是否被宣佈'noBookmarkView'弱的問題。還有什麼會提到這個觀點,並且可能會被釋放和歸零? –

+0

@GaryMakin我把它改成了'@IBOutlet var noBookmarkView:UIView!',它仍然有同樣的問題。 –

+0

這是我唯一的猜測,對不起。 –

回答

1

你應該通過UITableViewdataSource提供標題:

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

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

太棒了!這工作。我評論了第2節並添加了該代碼。我怎樣才能讓它只顯示標題,如果'self.idsb.count!= self.ids.count'? –

+0

您可以檢查'viewForHeaderInSection',如果不想顯示標題,則返回nil。您可能需要在'heightForHeaderInSection'中返回height = 0, – t4nhpt

+0

完美!非常感謝!! –