我是xcode / swift的新手。我遇到了在iPhone 4英寸屏幕中替换UITableViewCell中的UIImageView的问题。我在3中使用正确的图像嵌入图像:Assets.xcassets中的640,750,1242像素宽度。
TableView和ContentView约束[尾随空间,前导空间,底部空间到顶部空间]是从xCode完成的。
这就是我在tableview cellForRowAt中使用UIImageView的方式:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "reusedCell"
var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
if(cell == nil) {
cell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: identifier)
}
let image = UIImage(named: "TableView\(indexPath.row)")
let imageView = UIImageView(image: image)
cell?.addSubview(imageView)
imageView.contentMode = UIViewContentMode.scaleAspectFill
imageView.clipsToBounds = true
return cell!
}
图像在4.7英寸和5.5英寸iphone屏幕中尺寸正确,但在iphone 5,5s和SE中没有。
任何帮助/建议高度赞赏。 感谢
答案 0 :(得分:0)
您需要为imageView
:
let imageView = UIImageView(image: image)
cell?.addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
// for example
imageView.anchor(topAnchor, left: cell.leftAnchor, bottom: cell.bottomAnchor, right: cell.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
或创建自定义单元格:
class CustomTableViewCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let let imageView: UIImageView = {
let imgView = UIImageView()
imgView.translatesAutoresizingMaskIntoConstraints = false
imgView.contentMode = UIViewContentMode.scaleAspectFill
imgView.clipsToBounds = true
return imgView
}()
func setupViews() {
addSubview(imageView)
imageView.anchor(topAnchor, left: cell.leftAnchor, bottom: cell.bottomAnchor, right: cell.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
}
}
然后将您的函数 tableView 替换为:
let identifier = "reusedCell"
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: identifier) as ! CustomTableViewCell
let image = UIImage(named: "TableView\(indexPath.row)")
cell.imageView.image = image
return cell!
}