2017-06-06 63 views
0

我想添加填充到此自定义标题视图(图像)。UITableview添加填充到自定义部分标题imageview

该表是static content cells,我只是在第一部分添加图像。

我试图按照this链接,但不成功。

我想在标题视图中添加一些顶部和底部填充。

我想这没有运气:

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { 
    if section == 0 { 
     var header = tableView.tableHeaderView 
     let image = UIImage(named: "Placeholder") // is 121x121 
     let imageView = UIImageView(frame: CGRect(x: 0, y: 20, width: tableView.frame.width, height: tableView.sectionHeaderHeight)) 
     imageView.image = image 
     imageView.contentMode = .scaleAspectFit 
     header = imageView 
     return header 
    } 
    return nil 
} 

我也定义页眉高度委托:

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { 
    if section == 0 { 
     return 125.0 
    } 
    return 44.0 
} 

结果是没有填充相同。

任何帮助,将不胜感激

enter image description here

我也曾尝试到的ImageView添加到头部子视图导致整个图像消失英寸

+0

如果*表是'静态内容cells' *,你能添加它作为表本身的头?或者您是否需要图像作为第一部分的标题? – DonMag

回答

3

不是将UIImageView作为标题返回,而是将其作为子视图添加到UIView中,并在其中创建填充。

你的问题是,即使你为头设置了框架,UITableView也会调整它的大小以适应它的宽度和你设置为125的高度。因此,你必须将它包含在一个UIView中,填充表头,并包含你想给它填充的UIImageView。

编辑: 试试这个

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { 
    if section == 0 { 
     let header = UIView() 
     header.backgroundColor = UIColor.clear 
     let image = UIImage(named: "Placeholder") // is 121x121 
     let imageView = UIImageView(frame: CGRect(x: 0, y: 20, width: tableView.frame.width, height: tableView.sectionHeaderHeight)) 
     imageView.image = image 
     imageView.contentMode = .scaleAspectFit 
     header.addSubview(imageView) 
     return header 
    } 
    return nil 
} 
+0

这将整个图像从顶部填充20pt。我如何将它集中在上面,但在顶部和底部填充? – Simon

+0

只需将imageView的框架更改为您的需要。您可以尝试移动X并缩小宽度,高度应为-40,以便从顶部和底部获得相同的填充。 – TawaNicolas

+0

谢谢,结束了使用tableviews中心x属性,并减去它的图像尺寸width/2来获取框架: 'let imageView = UIImageView(frame:CGRect(x:tableView.center.x - (image.size .width/2),y:15.0,width:tableView.frame.width,height:0))' – Simon

相关问题