n.evermind
n.evermind

Reputation: 12004

Getting dimensions of an UITextView

I would like to determine the dimensions (especially number of lines) of a certain text string if placed in an UITextView with the dimensions 200 x 460 pixels, font Courier.

I tried to call the following method in order to get an integer which I can then display. However, it won't work (xCode tells me that I have incompatible types in the initialization):

NSString *temp2String;
    temp2String = [NSString stringWithFormat:@"%@",[textView text]];

    int strSize = [temp2String sizeWithFont:@"Courier" constrainedToSize:CGSizeMake(200, 10000)
                   lineBreakMode:UILineBreakModeWordWrap];

    NSString *temp2 = [[NSString alloc] initWithFormat:@"Size of string: %d", strSize];
    textViewSize.text = temp2;
    [temp2 release];

I am a beginner and I posted a similar question earlier today, but I still can't figure out how to get CGSize to work and give me the answer I need. Any help would be highly appreciated.

Upvotes: 0

Views: 584

Answers (2)

Till
Till

Reputation: 27597

CGSize is a structure (from CGGeometry.h):

struct CGSize {
  CGFloat width;
  CGFloat height;
};

Hence all you need to do is to fetch it and display whatever dimension you need to;

CGSize strSize = [temp2String sizeWithFont:@"Courier" constrainedToSize:CGSizeMake(200, 10000)
                   lineBreakMode:UILineBreakModeWordWrap];

Following your example (note the dimensions are given in float-values):

NSString *temp2 = [[NSString alloc] initWithFormat:@"Width of string: %f", strSize.width];
textViewSize.text = temp2;
[temp2 release];

Upvotes: 1

Dan Ray
Dan Ray

Reputation: 21893

CGSize is a struct. It contains two floats, named 'height' and 'width'.

CGSize strSize = [temp2String sizeWithFont:@"Courier" constrainedToSize:CGSizeMake(200, 10000)
                   lineBreakMode:UILineBreakModeWordWrap];
NSLog(@"Height %f, width %f", strSize.height, strSize.width);

Upvotes: 1

Related Questions