How to draw text in UITextView - ios

How to draw text in UITextView just like there is a method called "drawTextInRect:" in UILabel and UITextField. Should I implement it in "drawRect:" or "drawLayer:inContext:". Thank your focus and patient!

you can use drawinrect like following code.
UIFont *font = [UIFont fontWithName:#"Courier" size:kCellFontSize];
/// Make a copy of the default paragraph style
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
/// Set line break mode
paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
/// Set text alignment
paragraphStyle.alignment = NSTextAlignmentRight;
NSDictionary *attributes = #{ NSFontAttributeName: font,
NSParagraphStyleAttributeName: paragraphStyle };
[text drawInRect:rect withAttributes:attributes];

Related

IOS align text placeholder to be in the center and left alignment

I'm creating an IOS form that submits feed back.
I want to have placeholder text to be in the center vertically and left alignment horizontal in the text field
I have tried this
- (void)drawPlaceholderInRect:(CGRect)rect {
[RGB(36, 84, 157) setFill];
UIFont *font = [UIFont SingPostLightItalicFontOfSize:_placeholderFontSize fontKey:kSingPostFontOpenSans];
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
paragraphStyle.alignment = NSTextAlignmentLeft;
NSDictionary *attributes = #{ NSFontAttributeName: font,
NSParagraphStyleAttributeName: paragraphStyle,
NSForegroundColorAttributeName: [UIColor blackColor]};
[[self placeholder] drawInRect:rect withAttributes:attributes];
}
But the place holder text is on top vertical. How can we achieve the gold. Thanks a lot
The following code will solve your problem. I tried it myself. It's just one additional line to your code.
- (void)drawPlaceholderInRect:(CGRect)rect {
CGFloat fontSize = 18;
UIFont *font = [UIFont systemFontOfSize:fontSize];
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
paragraphStyle.alignment = NSTextAlignmentLeft;
NSDictionary *attributes = #{ NSFontAttributeName: font,
NSParagraphStyleAttributeName: paragraphStyle,
NSForegroundColorAttributeName: [UIColor blackColor]};
CGRect newRect = CGRectInset(rect, 0, rect.size.height/2 - fontSize/2);
[[super placeholder] drawInRect:newRect withAttributes:attributes];
}
You can put placeholder's "y" position means your "rect" value as a textfield height/2 .One more solution if you use default property of textfield for placeholder that would be horizontally aligned .
like as :
var tt : UITextField
tt.placeholder = ""

UILabel with multiple chained NSAttributedString, with line limit, show the tail truncation with NSBackgroundColorAttributeName of unseen text

The dots are added automatically by the UILabel, cause of line limitation, but they get the background color of hidden truncated text:
So I have UILabel with line limit of 10 and line break mode of TruncatingTail.
I also have 2 types of attributed strings that build this UILabel content.
NSForegroundColorAttributeName, NSFontAttributeName
NSBackgroundColorAttributeName, NSForegroundColorAttributeName, NSFontAttributeName
Any idea why the UILabel is adding background color to the dots? There is text in line 12 (which is truncated) that have that background...
=Here Given Code Try it..
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:#"test"];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
style.lineBreakMode = NSLineBreakByTruncatingTail;
[text addAttribute:NSParagraphStyleAttributeName
value:style
range:NSMakeRange(0, text.length)];
label.attributedText = text;
It looks like your NSAttributedString styling is picking up on an instance of "Windsor" that is past the truncation point.
You could find where the truncation occurs, and then only apply the text attribute to the range of the string up to the truncation point.
See this SO answer to calculate this range.
NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
paragraph.lineBreakMode = mylabel.lineBreakMode;
NSDictionary *attributes = #{NSFontAttributeName : mylabel.font,
NSParagraphStyleAttributeName : paragraph};
CGSize constrainedSize = CGSizeMake(mylabel.bounds.size.width, NSIntegerMax);
CGRect rect = [mylabel.text boundingRectWithSize:constrainedSize
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes:attributes context:nil];
if (rect.size.height > mylabel.bounds.size.height) {
NSLog(#"TOO MUCH");
}

UITextView: Background Color while keeping Left/Right Paragraph Indent

In my UITextView, I want certain NSRanges to be indented left and right equally and be highlighted in a specific color. I am achieving this by modifying NSMutableAttributedStrings and setting the textView.attributedText. To get the left/right indentation, I'm using NSMutableParagraphStyle - however, this is removing the highlighting (NSBackgroundColor). How can I get it such that the highlighting starts from the beginning, even with the headIndent.
// padding
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.headIndent = 5.0;
paragraphStyle.firstLineHeadIndent = 5.0;
paragraphStyle.tailIndent = -5.0;
NSDictionary *referenceAttributes = #{NSForegroundColorAttributeName: [UIColor lightGrayColor], NSBackgroundColorAttributeName: [UIColor brownColor], NSFontAttributeName: [UIFont fontWithName:#"HelveticaNeue-Bold" size: 14], NSParagraphStyleAttributeName: paragraphStyle};
Use following code to give padding in UITextView
self.textView.textContainer.lineFragmentPadding = 0;

How to set correctly the line height of UILabel with an AttributedString?

I have a UILabel which uses an Attributed String. I want to have its line height to be exactly the size of the font size, not a pixel bigger. However, a top and bottom padding are being added. See image below:
This is my code to create the label.
NSDictionary *basicAttributes = #{NSForegroundColorAttributeName: [UIColor whiteColor], NSBackgroundColorAttributeName: [UIColor blueColor]};
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:basicAttributes];
UIFont *font = [UIFont fontWithName:#"AvenirNext-Regular" size:20.0];
[attributes setObject:font forKey:NSFontAttributeName];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineHeightMultiple = 1.0f;
[attributes setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
self.helloWorldLabel.attributedText = [[NSMutableAttributedString alloc] initWithString:#"Hola" attributes:attributes];
Attempts
I have tried to call sizeToFit after setting the attributedText without success.
[self.helloWorldLabel sizeToFit];
I have played with other attributes of NSMutableParagraphStyle such as lineSpacing without success.
paragraphStyle.lineSpacing = 0.0f;
What am I missing?
Thanks in advanced
It sounds like you want to use boundingRectWithSize: Here's a short example of how to use it. This code will dynamically determine your label size based on the text in your label. Setting the constraining sizes allows a max size if content needs to overflow to multiple lines.
NSString *text = [NSString stringWithFormat:#"Title Header:%#", value];
NSRange boldRange = [text rangeOfString:#"Title Header:"];
NSRange normalRange = [text rangeOfString:value];
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text];
//Add attributes for appropriate ranges
[attributedText setAttributes:#{ NSFontAttributeName:[UIFont fontWithName:#"HelveticaNeue-Bold" size:13.0f]} range:boldRange];
[attributedText setAttributes:#{ NSFontAttributeName:[UIFont fontWithName:#"HelveticaNeue" size:13.0f]} range:normalRange];
//Determine rect for attributed text constrained within max values
CGRect textAttributedSize = [attributedText boundingRectWithSize:CGSizeMake(CellTitleWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:NULL];
[self.myLabel setText:attributedText];
[self.myLabel setFrame:textAttributedSize];
Check this link. There is no 100% way to correctly set the frame to fit the letters. You can calculate the attributed string with CoreText like using CTFramesetterRef CTFramesetterSuggestFrameSizeWithConstraints but it is more additional work.

Use sizeToFit with lineSpacing

I have a UILabel with several lines. The text is set dynamically, and my label height too, with this native method :
[myLabel sizeToFit];
I have an other method that sets the line spacing in my label :
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:#"My long dynamic text"];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:5];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
myLabel.attributedText = attributedString;
The problem is that even if I set the line spacing first, and then call sizeToFit, the new height of my label is to small. It doesn't take in count the line spacing.
It really is a problem as my label is in a UIScrollView and I need the right height.
For getting size of label dynamically based on text length use this method:
/*! Returns the size of the label to display the text provided
#param text
The string to be displayed
#param width
The width required for displaying the string
#param fontName
The font name for the label
#param fontSize
The font size for the label
*/
- (CGSize)getSizeForText:(NSString *)text maxWidth:(CGFloat)width font:(NSString *)fontName fontSize:(float)fontSize {
CGSize constraintSize;
constraintSize.height = MAXFLOAT;
constraintSize.width = width;
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:fontName size:fontSize], NSFontAttributeName,
nil];
CGRect frame = [text boundingRectWithSize:constraintSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributesDictionary
context:nil];
CGSize stringSize = frame.size;
return stringSize;
}
Try using – boundingRectWithSize:options:context: method of the NSMutableAttributedString. Refer the Apple Docs for more info.

Resources