user3126427
user3126427

Reputation: 855

How to change the view height dynamically based on content size?

I am trying add a xib file twice to the contentView and I want to change the height of the contentView based on the content size inside it.

This image shows what I want to achieve

enter image description here

here is my code

import UIKit

class ProfileSetViewController: UIViewController {

@IBOutlet weak var contentView: UIView!
@IBOutlet weak var contentViewHeight: NSLayoutConstraint!

override func viewDidLayoutSubviews() {

    if let CarViewAdd = NSBundle.mainBundle().loadNibNamed("CarViewAdd", owner: self, options: nil)[0] as? CarViewAdd {

        contentViewHeight.constant = 220
        contentView.frame.size.height = 220
        CarViewAdd.frame = CGRectMake(0, 0, self.contentView.frame.size.width, 220)
        CarViewAdd.carImage.layer.cornerRadius = 10
        CarViewAdd.carImage.clipsToBounds = true
        CarViewAdd.carImage.layer.borderColor = UIColor(red: 255/255, green: 0/255, blue: 0/255, alpha: 1.0).CGColor
        CarViewAdd.carImage.layer.borderWidth = 3
        contentView.addSubview(CarViewAdd)

    }

    if let CarViewAdd = NSBundle.mainBundle().loadNibNamed("CarViewAdd", owner: self, options: nil)[0] as? CarViewAdd {

        contentViewHeight.constant = 442
        contentView.frame.size.height = 442
        CarViewAdd.frame = CGRectMake(0, 222, self.contentView.frame.size.width, 220)
        CarViewAdd.carImage.layer.cornerRadius = 10
        CarViewAdd.carImage.clipsToBounds = true
        CarViewAdd.carImage.layer.borderColor = UIColor(red: 255/255, green: 0/255, blue: 0/255, alpha: 1.0).CGColor
        CarViewAdd.carImage.layer.borderWidth = 3
        contentView.addSubview(CarViewAdd)
    }

}

This is the result I get.

Notice the top xib picture is not displaying correctly. How can I fix this?

enter image description here

Upvotes: 1

Views: 982

Answers (2)

user3126427
user3126427

Reputation: 855

I fixed the problem by adding a UIView for each xib with the wanted frame for the xib file and then I add the xib to UIView with the same height and width.

Upvotes: 1

Radu Nunu
Radu Nunu

Reputation: 134

Try to change carImage.contentMode = .ScaleAspectFit

Upvotes: 0

Related Questions