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

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 = ""

Related

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");
}

Vertically centering a UITextField's attributedPlaceholder

I am currently unable to vertically align an attributedPlaceholder inside a UITextField and I've no idea why.
Here's what I am doing:
self.addressBar = [[UITextField alloc] initWithFrame: CGRectMake(...)];
self.addressBar.backgroundColor = [UIColor whiteColor];
self.addressBar.attributedPlaceholder = [[NSAttributedString alloc] initWithString:#"Placeholder text"
attributes:#{
NSForegroundColorAttributeName: [UIColor colorWithRed:79/255.0f green:79/255.0f blue:79/255.0f alpha:0.5f],
NSFontAttributeName : [UIFont fontWithName:#"Gotham-BookItalic" size:14.0],
}
];
self.addressBar.delegate = self;
self.addressBar.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
[self.view addSubview:self.addressBar];
And here's what happening:
It's quite clear that this happens due to the fact that the UITextFieldLabel's height is 10px smaller than the UItextField itself, but I can't seem change that.
This only happens using an attributedPlaceholder though; the default placeholder property works just fine.
Any ideas?
Use NSParagraphStyle to increase minimum line height:
NSMutableParagraphStyle *style = [self.addressBar.defaultTextAttributes[NSParagraphStyleAttributeName] mutableCopy];
style.minimumLineHeight = self.addressBar.font.lineHeight - (self.addressBar.font.lineHeight - [UIFont fontWithName:#"Gotham-BookItalic" size:14.0].lineHeight) / 2.0;
self.addressBar.attributedPlaceholder = [[NSAttributedString alloc] initWithString:#"Placeholder text"
attributes:#{
NSForegroundColorAttributeName: [UIColor colorWithRed:79/255.0f green:79/255.0f blue:79/255.0f alpha:0.5f],
NSFontAttributeName : [UIFont fontWithName:#"Gotham-BookItalic" size:14.0],
NSParagraphStyleAttributeName : style
}
];
You could also override a - (CGRect)placeholderRectForBounds:(CGRect)bounds; method in UITextField subclass.
It's messy, but it works :)
Placeholder will not be aligned if your textfield's text font is different than that of textfield's placeholder's font. Make sure both the font are same if you want to align properly or else you can follow kean's answer.
textField.font = [UIFont fontWithName:#"HelveticaNeue" size:12];
textField.attributedPlaceholder =
[[NSAttributedString alloc] initWithString:#"Enter fruit/vegetable name"
attributes:#{
NSFontAttributeName : [UIFont fontWithName:#"HelveticaNeue" size:12.0]
}
];
If you are using attributedPlaceholder, make sure to set the font of the textField to be the same font you use in the attributedString.
As #Kean answered. And you should do it like this in Swift 4:
let defaultParagraphValue = self.textField.defaultTextAttributes[NSAttributedStringKey.paragraphStyle.rawValue]
if let lineHeight = self.textField.font?.lineHeight,
let style = defaultParagraphValue as? NSParagraphStyle,
let mutableStyle = style.mutableCopy() as? NSMutableParagraphStyle {
mutableStyle.minimumLineHeight = lineHeight - (lineHeight - UIFont.systemFont(ofSize: 16).lineHeight) / 2.0
let placeholderAttribute = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 16),
NSAttributedStringKey.paragraphStyle: mutableStyle]
let attributeHolder = NSAttributedString(string: "Placeholder String",
attributes: placeholderAttribute)
self.textField.attributedPlaceholder = attributeHolder
}
This works in iOS 10, iOS 11 fix this issue.

How to draw text in UITextView

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

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.

Resources