无法在viewForHeaderInSection [UITableView]

时间:2016-10-07 04:34:28

标签: ios swift uitableview

我从API成功获取textLabel值。但无法设置 viewForHeaderInSection 。在我的应用程序中有不同的部分在不同的索引,意味着一些时间我得到两个部分,一些时间一个,一些时间三个

我正在尝试此代码 -

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let headerView = HeaderView(tableView: self.tblView, section: section)
        headerView.backgroundColor = UIColor.whiteColor()
        let subjectNameLabel = UILabel(frame: CGRect(x: 19, y: 4, width: 282, height: 35))

        subjectNameLabel.textAlignment = NSTextAlignment.Center
        subjectNameLabel.font = UIFont (name: "HelveticaNeue", size: 16)
        subjectNameLabel.textColor = UIColor.whiteColor()
        headerView.userInteractionEnabled = true

        let dataArrayTblView = dataArrayForTableView
        let subjectNameTxtValue = dataArrayTblView.valueForKey("subjectname")

        subjectNameLabel.text = subjectNameTxtValue as? String
        subjectNameLabel.backgroundColor = UIColor(red: 75/255.0, green: 193/255.0, blue: 210/255.0, alpha: 1.0)

        headerView.addSubview(subjectNameLabel)

        return headerView
    }

2 个答案:

答案 0 :(得分:1)

试试我的代码。

56

答案 1 :(得分:0)

以下是标题中正确的标题代码。您可以根据文本显示日期并设置宽度。

/ *

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    return self.showHeaderViewController(section)

}

func showHeaderViewController(section: Int) -> UIView {

    // Header View
    let headerView : UIView = UIView.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 35))
    headerView.backgroundColor = UIColor.clearColor()
    headerView.tag = section

    // Set Date on label
    let dateString  =  self.jsondata.objectAtIndex(section).valueForKey("Date") as! String


    //Get the width of String
    var sizeOfString = CGSize()
    if let font = UIFont(name: "Helvetica", size: 14.0)
    {
        let fontAttributes = [NSFontAttributeName: font] // it says name, but a UIFont works
        sizeOfString = (dateString as NSString).sizeWithAttributes(fontAttributes)
    }

    // Header View Label.
    let headerName = UILabel()
    headerName.frame = CGRectMake(0, 0, sizeOfString.width + 20 , 20)
    headerName.center = CGPointMake(UIScreen.mainScreen().bounds.width / 2, CGRectGetHeight(headerView.frame)/2)
    headerName.backgroundColor = UIColor(red: 139/255, green: 51/255, blue: 66/255, alpha: 1.0)
    headerName.textAlignment = .Center
    headerName.lineBreakMode = NSLineBreakMode.ByWordWrapping
    headerName.layer.cornerRadius = 7
    headerName.clipsToBounds = true
    headerName.font =  UIFont(name: "Helvetica", size: 14.0)
    headerName.textColor = UIColor.whiteColor()
    headerName.adjustsFontSizeToFitWidth = true
    headerName.numberOfLines = 0
    headerName.text = finalDate

    headerView.addSubview(headerName)

    return headerView

}

希望这对你有帮助。

感谢Mandeep Singh