2015-12-18 29 views
0

我试图将图像设置为UITableView的标题,虽然标题的大小不会调整为图像的大小。基于大量的研究(见我的编辑),我使用的是实现这一目标的相关代码如下:调整UIImage大小放置在UITableView的标题

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

    let frame = CGRectMake(0, 0, 300, 150) 
    let headerImageView = UIImageView(frame: frame) 
    let image: UIImage = UIImage(named: "reminder3.png")! 
    headerImageView.image = image 
    return headerImageView 
} 

func tableView(tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat { 

    return 150 
} 

它添加了图像的头,我可以调整大小头,但不管是什么我将它设置为高度值(目前为300),它始终保持恒定的大小。默认的头部大小。我无法调整标题以匹配我的尺寸UIImage。所以,我试着添加这个方法: 有没有人知道一个简单的方法来完成这个?

+0

你想tableView标题调整到你的UIImage高度(这不是300)? –

+0

的确如此,我使用300值作为测试人员 – John

+0

好的,您可以创建UIImage,然后询问其大小(image.size),然后创建具有该大小的tableView标头。不需要使用委托方法。 –

回答

1

您应该使用func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat代替,就像这样:

let img = UIImage(named: "image")! 

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { 
    return UIImageView(image: img) 
} 

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { 
    let w = view.frame.size.width 
    let imgw = img.size.width 
    let imgh = img.size.height 
    return w/imgw*imgh 
} 

仅使用estimatedHeightForHeaderInSection当你不知道确切的高度,它主要是用来确定的UITableView的滚动条位置。

+0

非常感谢你的解释和示例代码! – John

0
override func viewDidLoad() { 
    super.viewDidLoad() 

    //Create the UIImage 
    let image = UIImage(named: "testing") 

    //Check its size 
    print(image?.size) 

    //Create the UIImageView that will be our headerView with the table width 
    let imageView = UIImageView(frame: CGRect(x: 0.0, y: 0.0, width: self.tableView.bounds.width, height: image!.size.height)) 

    //Set the image 
    imageView.image = image 

    //Clips to bounds so the image doesnt go over the image size 
    imageView.clipsToBounds = true 

    //Scale aspect fill so the image doesn't break the aspect ratio to fill in the header (it will zoom) 
    imageView.contentMode = UIViewContentMode.ScaleAspectFill 

    //Set the tableHeaderView 
    self.tableView.tableHeaderView = imageView 
} 

我强烈建议你使用UIImage的扩展与AssetIdentifier枚举创建名称的UIImage的和他们建议在WWDC2015是类型安全的。