使用withVisualFormat在TableViewCell中定位元素

时间:2018-03-06 00:42:30

标签: swift xcode

使用下面的代码,我希望我的文字排列在我的标题下方,但它会被移动,如图中所示。我是使用withVisualFormat的新手,所以任何建议都会有所帮助。感谢

enter image description here

override init(style: UITableViewCellStyle, reuseIdentifier: String!)
    {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        self.imgIcon = UIImageView(image: UIImage(named: "icon_tack_b_f"))
        self.imgIcon.frame.size = CGSize(width: 40, height: 40)
        self.lblTitle = UILabel()
        self.lblText = UILabel()
        self.imgStatus = UIImageView(image: UIImage(named: "icon_checked"))
        self.imgStatus.frame.size = CGSize(width: 30, height: 30)

        imgIcon.translatesAutoresizingMaskIntoConstraints = false
        lblTitle.translatesAutoresizingMaskIntoConstraints = false
        lblText.translatesAutoresizingMaskIntoConstraints = false
        imgStatus.translatesAutoresizingMaskIntoConstraints = false

        contentView.addSubview(imgIcon)
        contentView.addSubview(lblTitle)
        contentView.addSubview(lblText)
        contentView.addSubview(imgStatus)

        let viewsDict = [
            "icon" : imgIcon,
            "title" : lblTitle,
            "text" : lblText,
            "status" : imgStatus,
            ] as [String : Any]

        contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[icon(40)]-[title]-[status(30)]-|", options: [], metrics: nil, views: viewsDict))
        contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[title]-[text]-|", options: [], metrics: nil, views: viewsDict))
        contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-40-[text]-30-|", options: [], metrics: nil, views: viewsDict))
    }

1 个答案:

答案 0 :(得分:1)

尝试在第一个视觉约束中设置对象之间的距离:

PUT

另外,不要忘记每张图片的高度

"H:|-0-[icon(40)]-0-[title]-0-[status(30)]-0-|"

所以,结果将是:

"V:|[icon(40)]"
"V:|[status(30)]"