Konstantinos Natsios
Konstantinos Natsios

Reputation: 2924

UIView dynamic height depending on Label Height

I have a Label which takes dynamicaly some data from database. These data are strings which can sometimes be 3-4-5 rows etc. So this labe is inside a UIView.

--UIView
  --Label

How can i make the UIView to take the certain height of the Label dynamicaly??

Upvotes: 9

Views: 25070

Answers (7)

Yusuf
Yusuf

Reputation: 981

Add left, top, right, and bottom constraints of the label to the view.

Set this property for the view

view.translatesAutoresizingMaskIntoConstraints = false

The view height will be dynamic by the label content size.

Upvotes: 0

BharathRao
BharathRao

Reputation: 2046

I know this is late answer, but it might help someone else.

To make the Dynamic height for UIView follow the simple steps in Storyboard

  1. Add a UIView in UIViewController and set your favourite background colour

enter image description here

  1. Now set the following constraints Leading, Top, Trailing and Height(as of now). We can adjust the Height constraint to achieve dynamic height further. enter image description here
  2. Update Height Constraints as shown below: enter image description here
  3. Now probably there storyboard will show you inequality constraint ambiguity. But we are going to fix this now. Just add a label inside UIView as shown enter image description here
  4. Now Set the Constraints for Label Leading, Trailing, Top and Bottom enter image description here
  5. Hurrah, Now the UIView height will increase based on the label's height. just make the following changes to label enter image description here

This technique works with other views inside this UIView. The thing is you must specify bottom constraints for the views present inside this UIView.

Upvotes: 9

Pavankumar
Pavankumar

Reputation: 288

- (IBAction)action:(id)sender {
self.label.text = @"UIImage *imageOne = [UIImage imageNamed:@RosePot.jpUIImageJPEGRepresentationg";
NSLog(@"%f",self.label.bounds.size.height);

float height = [self getHeightForText:@"UIImage *imageOne = [UIImage imageNamed:@RosePot.jpUIImageJPEGRepresentationg" withFont:[UIFont fontWithName:@"HelveticaNeue" size:15] andWidth:self.label.bounds.size.width];
NSLog(@"%f",height);
self.constraint.constant = height + self.viewOne.bounds.size.height;

}

-(float) getHeightForText:(NSString*) text withFont:(UIFont*) font andWidth:(float) width{
CGSize constraint = CGSizeMake(width , 20000.0f);
CGSize title_size;
float totalHeight;

SEL selector = @selector(boundingRectWithSize:options:attributes:context:);
if ([text respondsToSelector:selector]) {
    title_size = [text boundingRectWithSize:constraint
                                    options:NSStringDrawingUsesLineFragmentOrigin
                                 attributes:@{ NSFontAttributeName : font }
                                    context:nil].size;

    totalHeight = ceil(title_size.height);
} else {
    title_size = [text sizeWithFont:font
                  constrainedToSize:constraint
                      lineBreakMode:NSLineBreakByWordWrapping];
    totalHeight = title_size.height ;
}

CGFloat height = MAX(totalHeight, 40.0f);
return height;

}

enter image description here

Give leading ,top, trailing and height constraint for view .

And height outlet of view name as constraint [because i used outlet name constraint]

Upvotes: 1

praths
praths

Reputation: 353

first calculate the size of label with the text it contains, using this function

func calculateSizeOfLabel(text:String,labelWidth:CGFloat,labelFont:UIFont)->CGSize{
        let constrainedSize = CGSizeMake(labelWidth , 9999)

        var attributesDictionary:[String:AnyObject] = [:]

            attributesDictionary = [NSFontAttributeName:labelFont] as [String:AnyObject]



        let string:NSMutableAttributedString = NSMutableAttributedString(string:text, attributes:attributesDictionary)

        var boundingRect = string.boundingRectWithSize(constrainedSize, options:.UsesLineFragmentOrigin, context:nil)

        if (boundingRect.size.width > labelWidth) {
            boundingRect = CGRectMake(0,0, labelWidth, boundingRect.size.height);
        }


    return boundingRect.size
}

and then apply the height of returned size to the UIView like this

    let labelText = description.text
    let labelWidth = description.bounds.width
    let labelFont = description.font
    let calculatedHeight = calculateSizeOfLabel(labelText,labelWidth:labelWidth,labelFont:labelFont).height 
    DescView.frame = CGRectMake(DescView.frame.origin.x, DescView.frame.origin.y, DescView.bounds.width,calculatedHeight)

Upvotes: 3

balkaran singh
balkaran singh

Reputation: 2786

you can just do it with storyboard this pics

enter image description here

enter image description here

set the label height relation to greater than or equal

and set the view height relation to greater than or equal

it work like a magic

Upvotes: 9

PiterPan
PiterPan

Reputation: 1802

Bellow is working solution of your problem. I used autoLayout. In testView you don't set heightAnchor

let testView: UIView = {
    let view = UIView()
    view.translatesAutoresizingMaskIntoConstraints = false
    view.backgroundColor = UIColor.redColor()
    return view
}()

let testLabel: UILabel = {
    let label = UILabel()
    label.numberOfLines = 0
    label.translatesAutoresizingMaskIntoConstraints = false
    label.text = "jashfklhaslkfhaslkjdhflksadhflkasdhlkasdhflkadshkfdsjh"
    return label
}()


override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(testView)
    testView.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor).active = true
    testView.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor).active = true
    testView.widthAnchor.constraintEqualToConstant(100).active = true


    testView.addSubview(testLabel)
    testLabel.topAnchor.constraintEqualToAnchor(testView.topAnchor, constant: 10).active = true
    testLabel.leftAnchor.constraintEqualToAnchor(testView.leftAnchor, constant: 10).active = true
    testLabel.bottomAnchor.constraintEqualToAnchor(testView.bottomAnchor, constant: -10).active = true
    testLabel.rightAnchor.constraintEqualToAnchor(testView.rightAnchor, constant: -10).active = true

}

Upvotes: 6

PSS
PSS

Reputation: 316

Below code will resolved your issue :

//Adjust View Height

[yourView setFrame:CGRectMake(yourView.frame.origin.x, yourView.frame.origin.y, yourView.frame.size.width, yourLable.frame.size.height + yourLable.frame.origin.y + extraspace)];

Upvotes: 1

Related Questions