Search code examples
swiftuitableviewstoryboardconstraintsibdesignable

Design time crash while using programmatic constraints and @IBDesignable


I've been spinning my wheels for a couple days on this. I can't find any demonstrations of programmatic constraints with @IBDesignable.

  1. If I try imgv.translatesAutoresizingMaskIntoConstraints = false. Then an apparent infinite loop is set and I literally have to quit Xcode, reopen it and quickly delete it before design time occurs.

  2. As it is currently written, I have constraints that should change the imgv size to 200 width and height, but changing the values to 300 has no effect on the storyboard. So It is as if the constraints have no effect.

QUESTION: How can I create programmatic constraints which would display on storyboard using @IBDesignable?## Heading ##

import UIKit

@IBDesignable
class tryTVCellTableViewCell: UITableViewCell {

    override func prepareForInterfaceBuilder() {
        setProperties()
    }

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setProperties()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setProperties()
    }

    public override func layoutSubviews() {
        super.layoutSubviews()
        setProperties()
    }

    func setProperties() {
        backgroundColor = .blue
        let imgv = UIImageView(frame: CGRect(x: 10, y: 20, width: 50, height: 50))
        let bundle = Bundle(for: type(of: self))
        let img = UIImage(named: "mountain", in: bundle, compatibleWith: traitCollection)
        assert(img != nil)
        imgv.image = img
        imgv.backgroundColor = .green
        let lab = UILabel(frame: CGRect(x: 100, y: 10, width: 300, height: 300))
        lab.text = "hkjlkjlkj;lkj;lkj;lkj;lkj;lkj;lkj;lkj;lkj;lkj;lkj;lkj;lkj;lkj;lkj;lkj;lkj;l;lkjk;j;i"
        addSubview(imgv)
        addSubview(lab)


        imgv.widthAnchor.constraint(equalToConstant: 200).isActive = true
        imgv.heightAnchor.constraint(equalToConstant: 200).isActive = true
        imgv.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true

    }
}

Solution

  • Just try adding again

     imgv.translatesAutoresizingMaskIntoConstraints = false
    

    after

    addSubview(lab)
    

    before

    imgv.widthAnchor.constraint(equalToConstant: 200).isActive = true
    

    It should work.