简体   繁体   中英

Setting the height of UIlabel

I have a label that is in a custom uitableview cell. I am using auto layout to position the label. My question is how can one set the height of the label to zero when it does not have any text. Or how to to make the label height 0. The project supports ios 8 so using stackview is out of the question. The label is also expansive i can't set a constant height constraint.My layout is given below . 在此处输入图片说明

You can set label's height constraint >= 0. Label will update it's size to the content, and if text is missing height will be 0.

在此处输入图片说明

In tableviewcell give height constraints except UILabel which one you need to hide.Change your Tableviewcell height it works.

在此处输入图片说明

For example, Your UILabel height is '30' and tableviewcell height is 130.You can give 130-30 = 100 in cell height.

//only sample code
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row == 0 
    return 130
else 
    return 100

}

Another solution is possible that, set height constraint and take outlet of it and set it's constant to zero when text is nil.

Just ctrl + drag from height constraint to class to connect outlet to constraint.

then you can programatically change it's height when needed by changing it's constant.

for example,

@IBOutlet weak var labelHeightConstraint: NSLayoutConstraint!

and change constant like,

 self.labelHeightConstraint.constant = 0

Hope this will help :)

First set Height Constraint to Label. ctrl + drag the height Constraint to class to connect outlet to constraint. ie

@IBOutlet weak var LabelHeightConstraint: NSLayoutConstraint!

and in implementation set the Height Constraint of Label to zero. As shown below....

self.LabelHeightConstraint.constant = 0;
if(check the label contains data)
{
    self.LabelHeightConstraint.constant = 20;
}
else
{
    self.LabelHeightConstraint.constant = 0;
}

This Logic will surely work......

根据需要将文本设置为nil,并设置优先级高的内容

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM