我正在尝试添加3个标签&单个Tableview单元格中的3个图像。 这是我的标签&图像视图
let Namelbl:UILabel={
let label=UILabel()
label.text="item"
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let Namelbl2:UILabel={
let label2=UILabel()
label2.text="item"
label2.translatesAutoresizingMaskIntoConstraints = false
return label2
}()
let Namelbl3:UILabel={
let label3=UILabel()
label3.text="item"
label3.translatesAutoresizingMaskIntoConstraints = false
return label3
}()
let image1: UIImageView = {
let theImageView1 = UIImageView()
theImageView1.image = UIImage(named: "Masjid")
theImageView1.translatesAutoresizingMaskIntoConstraints = false
return theImageView1
}()
let image2: UIImageView = {
let theImageView2 = UIImageView()
theImageView2.image = UIImage(named: "Masjid2")
theImageView2.translatesAutoresizingMaskIntoConstraints = false
return theImageView2
}()
let image3: UIImageView = {
let theImageView3 = UIImageView()
theImageView3.image = UIImage(named: "Masjid3")
theImageView3.translatesAutoresizingMaskIntoConstraints = false
return theImageView3
}()
这是我使用约束设置视图的功能
func setupViews(){
addSubview(Namelbl)
addSubview(Namelbl2)
addSubview(Namelbl3)
addSubview(image1)
addSubview(image2)
addSubview(image3)
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-16-[v0]-16-[v1]-16-[v2]-16-[v3]-16-[v4]-16-[v5]-50-|",options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": Namelbl,"v1":Namelbl2,"v2":Namelbl3,"v3":image1,"v4":image2,"v5":image3]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": Namelbl]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": Namelbl2]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": Namelbl3]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": image1]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": image2]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": image3]))
}
问题是这适用于3个标签&一个图像不显示其他两个图像
答案 0 :(得分:1)
我建议不要在代码(*)中为您的单元格添加视图。我建议您设置表格视图以使用自定义单元格模板。然后,您可以使用链接到图像视图的出口定义UITableViewCell的自定义一个或多个子类,当您使用特定标识符出列单元格时,您将获得正确类的单元格,其中连接了出口并准备设置。您所要做的就是将其转换为正确的类型,然后配置它的视图。
(*)在代码中向单元格添加视图是更多的工作,它还需要特殊处理。如果您不小心,那么每次出列单元格时都会添加另一组视图。修复时,您需要一些机制来访问最初创建单元格时添加的视图,而使用viewWithTag(_:)
这样的典型方法很脆弱。