NSLineBreakByWordWrapping not working ios7

2019-08-05 13:26发布

问题:

I have a UILabel which is populated from the database .. the text in the UILabel can be long and can be short .. the problem is that the text is being cut at the end .. for example its shown like this: "www.sample.com/h1/h2/h3..." where it should be: "www.sample.com/h1/h2/h3/h4/h5/h6.html"

This is the code I am using:

CGFloat constraintWidth = 180.0f;

CGSize labelsize = [details.web sizeWithFont:self.webTextLabel.font constrainedToSize:CGSizeMake(constraintWidth, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];

CGRect webFrame = CGRectMake(20, self.webTitleLabel.frame.origin.y + self.WebTitleLabel.frame.size.height + 10, constraintWidth, labelsize.height);

[self.webLabel setFrame:webFrame];

[self.webLabel setText:details.web]; // details.web is where I get it from the database

self.webLabel .numberOfLines=0;

I am using Xcode 5 and iOS 7

SOLVED: I managed to solve it using this method:

UILabel *instructions = [[UILabel alloc]initWithFrame:CGRectMake(10, 225, 300, 180)];
   NSString *text = @"First take clear picture and then try to zoom in to fit the ";
   instructions.text = text;
   instructions.textAlignment = UITextAlignmentCenter;
   instructions.lineBreakMode = UILineBreakModeWordWrap;
   [instructions setTextColor:[UIColor grayColor]];

   CGSize expectedLabelSize = [text sizeWithFont:instructions.font 
                                constrainedToSize:instructions.frame.size
                                    lineBreakMode:UILineBreakModeWordWrap];

    CGRect newFrame = instructions.frame;
    newFrame.size.height = expectedLabelSize.height;
    instructions.frame = newFrame;
    instructions.numberOfLines = 0;
    [instructions sizeToFit];
    [self addSubview:instructions];

回答1:

Use following to get dynamic size of your text or label

 labelHeight = [details.web boundingRectWithSize:CGSizeMake(constraintWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSLineBreakByWordWrapping attributes:@{NSFontAttributeName:self.webTextLabel.font} context:nil];