UITextView position - iphone

Is there a way to find ypos in a UITextView, or/and find which row that currently marker is active?

you need to do some calculation
find cursor position by
NSRange cursorPosition = [tf selectedRange];
substring from cursor position use this sub string to calculate width of the string by
sizeWithFont:constrainedToSize:
and then divide it by width of the your TextView width.. it will give you at which line your cursor is... It's logically seems correct... haven't tried it... try it let me know if it is working or not..

Something like that:
- (int) getCurrentLine: (UITextView *) textView{
int pos = textView.selectedRange.location;
NSString *str =textView.text;
NSCharacterSet *charset = [NSCharacterSet whitespaceAndNewlineCharacterSet];
int num = pos;
for (; num< str.length; num++){
unichar c = [str characterAtIndex:num];
if ([charset characterIsMember:c]) break;
}
str = [str substringToIndex:num];
CGSize tallerSize = CGSizeMake(textView.frame.size.width - 16, 999999);
CGSize lc1 = [#"Yyg" sizeWithFont: textView.font constrainedToSize:tallerSize lineBreakMode:UILineBreakModeWordWrap];
CGSize lc = [str sizeWithFont: textView.font constrainedToSize:tallerSize lineBreakMode:UILineBreakModeWordWrap];
lc.height = lc.height / lc1.height;
return lc.height;
}

Related

UILabel is not displaying its correct value even if it is giving the newly assigned value in console

I have a UILabel which is displayed as a question. Its successfully displaying the question text which has been assigned to it programmatically. But later according to one if else condition, I have to change text in the label.Specifically I want to display an asterik(*) mark at the end of the string if that is a mandatory question.The * should be in red color and rest of the text should be in black.But it displays only the question not the * mark.If I try to print the questLabel.text it is giving the question with * mark at the end.Here is the code that I am trying
questText = questLabel.text;
questText = [questText stringByAppendingString:#"✶"];
NSMutableAttributedString * str = [[NSMutableAttributedString alloc] initWithString:questText];
NSMutableAttributedString *text =
[[NSMutableAttributedString alloc]
initWithAttributedString: str];
int length = (int)text.length;
[text addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor]
range:NSMakeRange(length-1, 1)];
[questLabel setAttributedText: text];
If I try to print the value of questLabel.attributedText :
Question{
}✶{
NSColor = "UIDeviceRGBColorSpace 1 0 0 1";
}
And the value for questLabel.text is :Question✶
Please help me out with this..Thanks in advance..
You should change your code to this.
NSString *questText = questLabel.text;
questText = [questText stringByAppendingString:#"✶"];
NSMutableAttributedString *text =
[[NSMutableAttributedString alloc] initWithString:questText];
int length = (int)text.length;
[text addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, length-1)];
[text addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(length-1, 1)];
[questLabel setAttributedText: text];
You can also try this
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:self.questLabel.text attributes:#{NSForegroundColorAttributeName:[UIColor blackColor]}];
NSMutableAttributedString *starString = [[NSMutableAttributedString alloc] initWithString:#"✶" attributes:#{NSForegroundColorAttributeName:[UIColor redColor]}];
[string appendAttributedString:starString];
[self.questLabel setAttributedText:string];

Counting whitespace and blanks in UILabel text

I have a strike-out subview in my cell's labels and its width is set accordingly to the text in the row. The number of lines in the cell's label is set to 2, and when there are two lines I have two strike-outs set on the label.
This is what I'm doing for labels with just one line of text:
UIView *crossout = [[UIView alloc] init];
crossout.frame = CGRectMake(x, y, w + 5, 2);
crossout.backgroundColor = [UIColor colorWithRed: 0.0 / 255 green:175.0 / 255 blue: 30.0 / 255 alpha:1.0];
crossout.tag = 1;
[self.contentView addSubview:crossout];
I'm getting the width (w) by:
CGFloat w = [self.label.text sizeWithFont:[UIFont systemFontOfSize:15.0f]].width;
When I have a second strike-out, I simply subtract w from the length of my label to get the width of the second strike-out.
Problem though is that w doesn't account for white spaces or blanks in the label's text, so it won't always look consistent across the line breaks.
How do I calculate w so that it includes the white spaces and blanks?
as i know you can use this for UITextField but you can give it a try..
NSString *resultingString = self.label.text;
NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet];
if ([resultingString rangeOfCharacterFromSet:whitespaceSet].location == NSNotFound) {
//here you can put your code
}
To get the number of in-line whitespaces in your string you could try the following code:
NSCharacterSet* whitespaceSet = [NSCharacterSet whitespaceCharacterSet];
NSArray* substringsArray = [yourStringToCheck componentsSeparatedByCharactersInSet: whitespaceSet]
NSLog(#"Number of whitespaces : %d", [substringsArray count]);
Or, maybe even better (allthough this probably doesn't account for tabs etc.):
NSLog(#"Number of whitespaces : %d", [[yourStringToCheck componentsSeparatedByString:#" "] count]);
Another option (NSMutableString):
NSUInteger replacementCount = [yourStringToCheck replaceOccurrencesOfString:#" " withString:#" " options:NSLiteralSearch range:NSMakeRange(0, [receiver yourStringToCheck])];

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.
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];
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);

UILabel visible part of text

Is there a way to get the visible part of text in word wrapped UILabel? I mean exactly the last visible character?
I'd like to make two labels rounding the image and would like to continue the text which was out of rect for first label on the second one.
I know [NSString sizeWithFont...] but are there something reversing like [NSString stringVisibleInRect: withFont:...] ? :-)
Thank you in advance.
You could use a category to extend NSString and create the method you mention
#interface NSString (visibleText)
- (NSString*)stringVisibleInRect:(CGRect)rect withFont:(UIFont*)font;
#end
#implementation NSString (visibleText)
- (NSString*)stringVisibleInRect:(CGRect)rect withFont:(UIFont*)font
{
NSString *visibleString = #"";
for (int i = 1; i <= self.length; i++)
{
NSString *testString = [self substringToIndex:i];
CGSize stringSize = [testString sizeWithFont:font];
if (stringSize.height > rect.size.height || stringSize.width > rect.size.width)
break;
visibleString = testString;
}
return visibleString;
}
#end
Here's a O(log n) method with iOS 7 APIs. Only superficially tested, please comment if you find any bugs.
- (NSRange)hp_visibleRange
{
NSString *text = self.text;
NSRange visibleRange = NSMakeRange(NSNotFound, 0);
const NSInteger max = text.length - 1;
if (max >= 0)
{
NSInteger next = max;
const CGSize labelSize = self.bounds.size;
const CGSize maxSize = CGSizeMake(labelSize.width, CGFLOAT_MAX);
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.lineBreakMode = self.lineBreakMode;
NSDictionary * attributes = #{NSFontAttributeName:self.font, NSParagraphStyleAttributeName:paragraphStyle};
NSInteger right;
NSInteger best = 0;
do
{
right = next;
NSRange range = NSMakeRange(0, right + 1);
NSString *substring = [text substringWithRange:range];
CGSize textSize = [substring boundingRectWithSize:maxSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil].size;
if (textSize.width <= labelSize.width && textSize.height <= labelSize.height)
{
visibleRange = range;
best = right;
next = right + (max - right) / 2;
} else if (right > 0)
{
next = right - (right - best) / 2;
}
} while (next != right);
}
return visibleRange;
}

Why is my sizeWithFont:constrainedToSize:lineBreakMode: always returning zero?

I'm trying to make a UITableViewCell that adjusts its height based on the length of a string it's displaying, but am getting hung up on this method.
Here's what I've got:
NSString *text = #"A really long string in here";
CGSize theSize = [text sizeWithFont:[UIFont boldSystemFontOfSize:18.0f] constrainedToSize:CGSizeMake(265.0f, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
NSString *stringHeight = [NSString stringWithFormat:#"%d", theSize.height];
No matter what, stringHeight displays as 0. What am I missing?
Thanks!
CGFloats correspond to the C float data type; the proper format specifier for them is %f:
NSString *text = #"A really long string in here";
CGSize theSize = [text sizeWithFont:[UIFont boldSystemFontOfSize:18.0f] constrainedToSize:CGSizeMake(265.0f, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap];
NSString *stringHeight = [NSString stringWithFormat:#"%f", theSize.height];
Also, you should use CGFLOAT_MAX instead of MAXFLOAT
You could also use
NSStringFromCGSize(theSize);