search

Home  >  Q&A  >  body text

objective-c - 用约束调整label,如何利用约束计算其父控件的动态高度

  1. 描述你的问题
    在storyboard上 拖一个view 设置好约束, 拖一个label ,设置左、上、宽度约束,label 文字变化的时候view 高度也要跟随变化,如何计算label文字变化

  2. 贴上相关代码

-(void)touchesBegan:(NSSet<UITouch > )touches withEvent:(UIEvent *)event
{

// self.oriangeView.bounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(self.oriangeView.bounds), CGRectGetHeight(self.label.bounds));

[self.oriangeView setNeedsLayout];
[self.oriangeView layoutIfNeeded];
// 得到cell的contentView需要的真实高度
CGFloat height = [self.oriangeView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;

// 要为cell的分割线加上额外的1pt高度。因为分隔线是被加在cell底边和contentView底边之间的。
height += 1.0f;
NSLog(@"%f",height);

}

  1. 贴上报错信息

  2. 贴上相关截图

  3. 已经尝试过哪些方法仍然没解决(附上相关链接)

ringa_leeringa_lee2757 days ago644

reply all(1)I'll reply

  • 大家讲道理

    大家讲道理2017-05-02 09:20:30

    @interface ViewController ()
    @property (weak, nonatomic) IBOutlet UILabel *label;
    @property (weak, nonatomic) IBOutlet UIView *oriangeView;
    @property (weak, nonatomic) IBOutlet NSLayoutConstraint *upConstraint;
    @property (weak, nonatomic) IBOutlet NSLayoutConstraint *smallViewConstraint;

    @end

    @implementation ViewController

    • (void)viewDidLoad {

      [super viewDidLoad];
      // Do any additional setup after loading the view, typically from a nib.
      self.label.text = @"嘎哈和嘎哈了韩国辣和韩国人哈哈给扔了过来哈日韩国和腊肉和嘎哈和认购或利润阿尔哈嘎哈恶化然后给hlahahghlalhrh了哈哈个哈哈入行后任何两个哈喽哈嘎哈了和老公哈理工哈哈额合格和拉和老公哈哈嘎哈和嘎哈和嘎哈恩会更好还染了个哈哈好了噶好了好给力哈尔和噶哈哈噶呵呵旮旯儿回来给海拉尔和爱好了和";
      self.label.textAlignment = NSTextAlignmentLeft;
      self.label.font =[UIFont systemFontOfSize:15];

      // [self.oriangeView layoutIfNeeded];

    // [self.oriangeView updateConstraints];

    }

    pragma mark--- 根据字符串和字体求字符串高度

    -(CGSize)stringSizeWithFont:(UIFont )font string:(NSString )string width:(CGFloat)width
    {

    
    CGRect rect =[string boundingRectWithSize:CGSizeMake(width, 10000) options: NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil];
    return rect.size;

    }
    -(void)touchesBegan:(NSSet<UITouch > )touches withEvent:(UIEvent *)event
    {

    CGFloat height = 0;
    self.label.text = @"嘎哈和嘎哈了韩国辣和韩国人哈哈给扔了过来哈日韩国和腊肉和嘎哈和认购或利润阿尔哈嘎哈恶化然后给hlahahghlalhrh了哈哈个哈哈入行后任何两个哈喽哈嘎哈了和老公哈理工哈哈额合格和拉和老公哈哈嘎哈和嘎哈和嘎哈恩会更好还染了个哈哈好了噶好了好给力哈尔和噶哈哈噶呵呵旮旯儿回来给海拉尔和爱好了和嘎哈和嘎哈了韩国辣和韩国人哈哈给扔了过来哈日韩国和腊肉和嘎哈和认购或利润阿尔哈嘎哈恶化然后给hlahahghlalhrh了哈哈个哈哈入行后任何两个哈喽哈嘎哈了和老公哈理工哈哈额合格和拉和老公哈哈嘎哈和嘎哈和嘎哈恩会更好还染了个哈哈好了噶好了好给力哈尔和噶哈哈噶呵呵旮旯儿回来给海拉尔和爱好了和";
    height = [self stringSizeWithFont:[UIFont systemFontOfSize:15] string:self.label.text width:self.label.frame.size.width].height +self.upConstraint.constant ;
    NSLog(@"动态返回高度%f",height);
    self.smallViewConstraint.constant =height;
    [UIView animateWithDuration:2 animations:^{
        [self.oriangeView layoutIfNeeded];
    }];

    }

    reply
    0
  • Cancelreply