我正在尝试将图像设置为'UITableView cell background.I create
UIiImageView in
cellforRowAt` func并将其添加到单元格作为subView,但结果是:
仅适用于第一个细胞。我在cellForRowAt
函数中的代码:
let imageView = UIImageView(frame: CGRect(x: cell.frame.origin.x - 10 , y: cell.frame.origin.y - 20 , width: cell.frame.size.width + 20 , height: cell.frame.size.height ))
let image = UIImage(named: "sentimg")
imageView.image = image
cell.backgroundView = UIView()
cell.backgroundView!.addSubview(imageView)
答案 0 :(得分:1)
您应该在cell.bounds
中使用cell.frame
代替let imageView = UIImageView(frame: CGRect(x: cell.frame.origin.x - 10 , y: cell.frame.origin.y - 20 , width: cell.frame.size.width + 20 , height: cell.frame.size.height ))
,cell.frame
将在其superView中引用该单元格的位置,而cell.bounds
将引用该位置相对于它自己,这就是你需要的,因为你将你的图像添加为细胞子视图
类似
let imageView = UIImageView(frame: CGRect(x: cell.bounds.origin.x - 10 , y: cell.bounds.origin.y - 20 , width: cell.bounds.size.width + 20 , height: cell.bounds.size.height ))`
答案 1 :(得分:0)
或者更好的是,使用自动布局约束:
let imageView = UIImageView(image: UIImage(named: "sentimg"))
let backgroundView = UIView()
imageView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
imageView.leftAnchor.constraint(equalTo: backgroundView.leftAnchor, constant: -10),
imageView.rightAnchor.constraint(equalTo: backgroundView.rightAnchor, constant: 10),
imageView.topAnchor.constraint(equalTo: backgroundView.topAnchor, constant: -20),
imageView.bottomAnchor.constraint(equalTo: backgroundView.bottomAnchor, constant: -20),
])
cell.backgroundView = backgroundView