调整放置在 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的大小。因此,我尝试添加此方法:有人知道实现这一点的简单方法吗?

您应该使用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的滚动条位置。

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上的建议进行类型安全。

最新更新