Bharat Bharat - 3 years ago 158
iOS Question

UIView not adjusting width according to subviews?

I'm trying to creating a reusable

UIView subclass
, with a
. My view subclass should adjust its width according to the label's width.

Here is my class-

class CustomView: UIView {
private var infoLabel: UILabel!
private var imageView: UIImageView!

override init(frame: CGRect) {
super.init(frame: frame)
infoLabel = UILabel(frame:
imageView = UIImageView(frame:

infoLabel.backgroundColor = .white
imageView.backgroundColor = .gray
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)

override func updateConstraints() {
infoLabel.translatesAutoresizingMaskIntoConstraints = false
imageView.translatesAutoresizingMaskIntoConstraints = false

equalTo: self.leadingAnchor, constant: 5).isActive = true
// infoLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
infoLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 5).isActive = true
infoLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 5).isActive = true

equalTo: infoLabel.trailingAnchor, constant: 10).isActive = true
//equalTo: self.trailingAnchor, constant: 10).isActive = true
//imageView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
imageView.widthAnchor.constraint(equalToConstant: 25).isActive = true
imageView.topAnchor.constraint(equalTo: self.topAnchor, constant: 5).isActive = true
imageView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 5).isActive = true

internal func setText(_ text: String, andImage image: String){
infoLabel.text = text
imageView.image = UIImage(named: image)

and here is how I'm adding it to view -

let aView: CustomView = CustomView(frame: CGRect(x: 20, y: 144, width: 120, height: 31))
aView.setText("my testing label", andImage: "distanceIcon")
aView.backgroundColor =

I get the result like added image.(red is my custom view, white is label and gray is image)
enter image description here

Edit: It is working if add view in Storyboard and but if I try via code as mentioned above it is not working.

Answer Source

You have to call translatesAutoresizingMaskIntoConstraints = false on CustomView class instance as well:

self.translatesAutoresizingMaskIntoConstraints = false

Also add leading and top constraints on custom view to set it's position:

customView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 200).isActive = true
customView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 200).isActive = true

Don't forget to add trailing constraint on imageView:

imageView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -10).isActive = true
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download