首页 > 解决方案 > 如何修复表格视图单元格文本标签间距

问题描述

如何修复单元格的文本标签在文本和图像之间有不同的间距如何解决此表是通过编码创建的

class NewMessageCell: UITableViewCell {

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}



override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
}

override func layoutSubviews() {
    super.layoutSubviews()
    self.imageView?.frame = CGRect(x: 5, y: 10, width: 70, height: 70)
    self.imageView?.clipsToBounds = true
    self.textLabel?.highlightedTextColor = UIColor.blue

}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

}

表格图像

标签: swift

解决方案


self.imageView?.frame = CGRect(x: 5, y: 10, width: 70, height: 70)

如果你设置 UIImageView 的边界,那么它会搞砸。UIImageView 将自动填充单元格的大小,因此如果您以编程方式创建视图,您可以控制整个视图的大小。

如果您需要将所有图像设置为新大小以便它们工作,请使用此功能(我从这个问题为 iOS 10 更新了它:

func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
    let size = image.size

    let widthRatio  = targetSize.width  / size.width
    let heightRatio = targetSize.height / size.height

    // Figure out what our orientation is, and use that to form the rectangle
    var newSize: CGSize
    if(widthRatio > heightRatio) {
        newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
    } else {
        newSize = CGSize(width: size.width * widthRatio,  height: size.height * widthRatio)
    }

    // This is the rect that we've calculated out and this is what is actually used below
    let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)

    // Actually do the resizing to the rect using the ImageContext stuff
    return UIGraphicsImageRenderer(size: newSize).image { ctx in
        image.draw(in: rect)
    }
}

推荐阅读