Placeholder text not centered for UITextField created programmatically - iphone

I am creating a UITextField programmatically and placing it inside a UIView. The font size is set to 15.0f (system font). But the placeholder that appears is not centered in the text view. Any one know how to resolve this?
I found some references on SO for blurred text etc and tried setting the frame of the textfield with integer values, but it doesn't make a difference.
UITextField *txtField = [[UITextField alloc] initWithFrame:CGRectMake(5.0f, 6.0f, 278.0f, 32.0f)];
[txtField setPlaceholder:#"My placeholder"];
[txtField setFont:[UIFont systemFontOfSize:15.0]];
[txtField setBorderStyle:UITextBorderStyleRoundedRect];
[txtField setAutocorrectionType:UITextAutocorrectionTypeNo];
[txtField setAutocapitalizationType:UITextAutocapitalizationTypeNone];
[txtField setKeyboardType:UIKeyboardTypeEmailAddress];
[txtField setReturnKeyType:UIReturnKeyDone];
[txtField setClearButtonMode:UITextFieldViewModeWhileEditing];
Thank you for any help
Note: I mean that the text is not centered vertically in the textfield (it is a bit towards the top). So setting the text alignment is not the solution.
Adding an image of the issue for clarification - as seen in the image, the placeholder text is more towards the top and not in the center vertically.

You need to add:
txtField.textAlignment = NSTextAlignmentCenter; // Pre-iOS6 SDK: UITextAlignmentCenter
Keep in mind, this adjusts both the alignment of the placeholder text as well as the text the user will enter in.
How to center vertically
Since the original question was updated to request how to vertically align the placeholder text and that answer is buried in the comments, here is how to do that:
txtField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;

This does not work as expected on iOS7. On iOS7 you will have to override TextField class and
- (void) drawPlaceholderInRect:(CGRect)rect
method.
Like this:
- (void) drawPlaceholderInRect:(CGRect)rect
{
[[UIColor blueColor] setFill];
CGRect placeholderRect = CGRectMake(rect.origin.x, (rect.size.height- self.font.pointSize)/2, rect.size.width, self.font.pointSize);
[[self placeholder] drawInRect:placeholderRect withFont:self.font lineBreakMode:NSLineBreakByWordWrapping alignment:self.textAlignment];
}
Works for both iOS7 and earlier versions.

I was using just the color, but we need to set the font as well.
This one worked for me:
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setDefaultTextAttributes:
#{
NSForegroundColorAttributeName:[UIColor whiteColor],
NSFontAttributeName: [UIFont systemFontOfSize:12]
}];

Changing the minimum line height using NSParagraphStyle was the only solution that worked for me:
NSMutableParagraphStyle *style = [self.addressBar.defaultTextAttributes[NSParagraphStyleAttributeName] mutableCopy];
style.minimumLineHeight = self.addressBar.font.lineHeight - (self.addressBar.font.lineHeight - placeholderFont.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 : placeholderFont,
NSParagraphStyleAttributeName : style
}];

Related

UITextView text vertical Alignment

I have created Custom UITextView class ,where textView grows dynamically as user types characters and textview frame resized dynamically.I want to align the text vertically center in the frame,it always coming to bottom by default.I added UIEdgeInsets to make or look a like it into center but it creates more issues for me.If i try to set content offset then the textView center also shifts.Is the content offset and textView center effect each other ?.I want textview center where ever it is but the text inside the textView stays vertically center.
Initially i am setting UITextView font 23.0 with a rectangular border(textview frame layer border).When i start typing in that box the text is coming on bottom of the border.Then i am using
[textView setContentInset:UIEdgeInsetsMake(5,0,10,0)];
to make text in center. Then i have to send this text for printing which is placed on an UIImageView.Here i am using the mentioned code by Paras to match printer dpi and resizing it.But the text as looks on UIImageview doesn't match the exact placement of print because i have added UIEdgeInset to adjust vertical alignment
I have two types to set dynamic height to the UITextView see both are bellow...
UPDATE:
First Create UITextView programmatically like bellow...
-(IBAction)btnAddTextView:(id)sender
{
UIView *viewTxt = [[UIView alloc]initWithFrame:CGRectMake(imgBackBoard.center.x - 100,20, 220, 84)];
[viewTxt setBackgroundColor:[UIColor clearColor]];
viewTxt.userInteractionEnabled = YES;
UITextView *txtAddNote=[[UITextView alloc]initWithFrame:CGRectMake(20,20, 180, 44)];
[txtAddNote setBackgroundColor:[UIColor scrollViewTexturedBackgroundColor]];
[txtAddNote setFont:[UIFont fontWithName:#"Helvetica-Bold" size:15]];
txtAddNote.layer.borderWidth = 2.0;
txtAddNote.layer.borderColor= [UIColor redColor].CGColor;
viewTxt.tag = 111;
txtAddNote.tag = 111;
txtAddNote.userInteractionEnabled= YES;
txtAddNote.delegate = self;
txtAddNote.textColor = [UIColor whiteColor];
[viewTxt addSubview:txtAddNote];
[viewBoard addSubview:viewTxt];
[txtAddNote release];
}
First
1. This bellow Method is Delegate Method of UITextViewDelegate.
in .h class add this UITextViewDelegate and then give your textView.delegate to self like bellow..
yourTextView.delegate = self;
and use paste this bellow method...
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
textView.frame = CGRectMake(textView.frame.origin.x, textView.frame.origin.y, textView.frame.size.width, textView.contentSize.height);
return YES;
}
here when your UITextView editing at a time with its text, the content size of textView is change.
2. Use my bellow custom Method for set Dynamic Height of UILable,UITextField and also UITextView
-(float) calculateHeightOfTextFromWidth:(NSString*) text: (UIFont*)withFont: (float)width :(UILineBreakMode)lineBreakMode
{
[text retain];
[withFont retain];
CGSize suggestedSize = [text sizeWithFont:withFont constrainedToSize:CGSizeMake(width, FLT_MAX) lineBreakMode:lineBreakMode];
[text release];
[withFont release];
return suggestedSize.height;
}
use this method like bellow...
CGSize sizeToMakeLabel = [yourTextView.text sizeWithFont:yourTextView.font];
yourTextView.frame = CGRectMake(yourTextView.frame.origin.x, yourTextView.frame.origin.y,
sizeToMakeLabel.width, sizeToMakeLabel.height);

UITextView background image does not fit in frame size of UITextView frame

I am developing an app where I need to put a UITextView for the large text. I have a background image of size 180X89(same as UITextView frame size). When put the image behind the UITextView, everything appears good however, when the user hits the text area and keyboard appears, the cursor appears just outside the edge of the image.
I want the cursor to be appeared in textbox.
Code for getting UITextview
CGRect textViewFrame = CGRectMake(125.0f, 155.0f, 180.0f, 90.0f);
UITextView *textView = [[UITextView alloc] initWithFrame:textViewFrame];
textView.returnKeyType = UIReturnKeyDone;
textView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed: #"textbox.png"]];
textView.delegate = self;
[self.view addSubview:textView];
Try this:
UIImage *bgImage = [UIImage imageNamed:#"textbox.png"];
UIImageView *bgImageView = [[UIImageView alloc] initWithImage:bgImage];
CGRect textViewFrame = CGRectMake(125.0f, 155.0f, 180.0f, 90.0f);
bgImageView.frame = textViewFrame;
UITextView *textView = [[UITextView alloc] initWithFrame:textViewFrame];
textView.returnKeyType = UIReturnKeyDone;
textView.delegate = self;
[self.view addSubview:bgImageView];
[self.view addSubview:textView];
Or something like it.
There is very simple approach. Just use UIImageView behind the TextView and set UITextView Background color as clear color.
What you can do in such situations is to make the size of the UITextView a bit smaller so that it just comes in ur background image and also give the UITextView a corner radius using the framework <QuartzCore> like textview.layer.cornerRadius = 10; (import the header for the framework). This approach would also give the UITextView edges a bit of roundness to make it look like the image u provided above.
So, in short add the UIImageView then add the UITextView above it and make the background of the textview as clearcolor . Hope this helps !!! :)
Add UIImageView on your view, Then add UITextView on UIImageView with inner frame of
CGPointMake(10,10) as Origin
and CGSizeMake(imageView.frame.size.width - 20.0, imageView.frame.size.hieght - 20.0) as Size of textView.

Customize UILabel's Behavior

I am new to iphone.i found UILabel instance methodes very hard for me to implement.how can i use it.how can i customize the appearance of your text of a UIlabel further by subclassing UILabel.Plz i need little help to initiate.Foe example i have a label in my viewController how can i custmize it's text and hoe to subclass
.thanks in advance.
You can use so many properties of a UILabel like:
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 100, 40)];
lbl.font = [UIFont fontWithName:#"Helvetica" size:12.0]; // For setting font style with size
lbl.textColor = [UIColor whiteColor]; //For setting text color
lbl.backgroundColor = [UIColor clearColor]; // For setting background color
lbl.textAlignment = UITextAlignmentCenter; // For setting the horizontal text alignment
lbl.numberOfLines = 2; // For setting allowed number of lines in a label
lbl.lineBreakMode = UILineBreakModeWordWrap; // For setting line break mode
lbl.text = #"TitleText"; // For setting the text inside the label
Let me know if any thing other than this you want to know!!
The two methods
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
return CGRectInset(bounds, MARGIN, MARGIN);
}
- (void)drawTextInRect:(CGRect)rect
{
[super drawTextInRect: CGRectInset(self.bounds, MARGIN, MARGIN)];
}
We are using CGRectInset to create a rectangle that is either larger or smaller than an existing rectangle (bounds).
For Smaller rectangle, use positive values as MARGIN
For Larger rectangle, use positive values as MARGIN
All the best!!!

UILabel size to fit

I have a problem involving UILabel's sizeToFit method:
UILabel *questionLabel = [[UILabel alloc]initWithFrame:CGRectMake(0,0,320,320)];
questionLabel.lineBreakMode = UILineBreakModeWordWrap;
questionLabel.backgroundColor=[UIColor clearColor];
questionLabel.textAlignment=UITextAlignmentLeft;
questionLabel.textColor=[UIColor blackColor];
questionLabel.tag=1;
questionLabel.font=[UIFont systemFontOfSize:13];
questionLabel.numberOfLines = 0;
[questionLabel sizeToFit];
[myView addSubview:questionLabel];
I had written this code for displaying my data. But if I write: [questionLabel sizeToFit] my data does not display properly. If I remove [questionLabel sizeToFit] then it is displaying but it only shows half the data.
Thanks and Regards.
NSString *yourString = #"write your label text here";
CGSize s = [yourString sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:CGSizeMake(width, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
questionLabel.frame = CGRectMake(0, 0, s.width, s.height);
Check if it helps.
I think it's best to use taus-iDeveloper answer to compute the size of a label.
I just want to say that the reason your code is not working is because you didn't set text to your UILabel so sizeToFit returns CGSizeZero (so it doesn't appear on screen). You have to set text before using sizeToFit.
I found that if AutoLayout is on then size to fit not work
i googled d above problem and came across some info that sizeToFit seems to be a bug and it has been reported to apple already.
So as a workaround u can use this code:
NSString * myText = [NSString stringWithString:#"some text"];
CGFloat constrainedSize = 265.0f;
UIFont * myFont = [UIFont fontWithName:#"Arial" size:19];
CGSize textSize = [myText sizeWithFont: myFont
constrainedToSize:CGSizeMake(constrainedSize, CGFLOAT_MAX)
lineBreakMode:UILineBreakModeWordWrap];
CGRect labelFrame = CGRectMake (0, 0, textSize.width, textSize.height);
UILabel *label = [[UILabel alloc] initWithFrame:labelFrame];
[label setFont:myFont];
[label setText:myText];
I've found that when using sizeToFit with a UILabel, in InterfaceBuilder you need to change the Autoshrink property from 'Fixed Font Size' to 'Minimum Font Size'. I usually then set its value to 0.5 to be sure its working properly.
just make sure you increase the number of lines of the label. Instead of
questionLable.numberOfLines = 0; make use of
questionLable.numberOfLines = 4;
As it will force the system to compute the smallest width possible for 4 lines.
You can achieve this via the Xib file too..

How to use UIView's contentStretch

I want to use an image of size 27x27 with the center 1 pixel stretchable as the backgroundImage of an UIButton. Here is my code:
[button setBackgroundImage:[UIImage imageNamed:#"button_image"] forState:UIControlStateNormal];
button.frame = CGRectMake(0.f, 0.f, 27.f, 27.f);
button.contentStretch = CGRectMake(13.f/27.f, 13.f/27.f, 1.f/27.f, 1.f/27.f);
[button setTitle:NSLocalizedString(#"long title", #"long title") forState:UIControlStateNormal];
[button sizeToFit];
CGRect buttonFrame = button.frame;
buttonFrame.size.width += 18.f * 2;
button.frame = buttonFrame;
But the result is no different from that without setting contentStretch at all.
So how to correctly use contentStretch to achieve what I want?
Please don't tell me again and again that I can achieve the same effect with stretchableImageWithLeftCapWidth:topCapHeight:. I know that and it's apparently not what I'm asking for. I just want to know how to properly use contentStretch. Thanks.
One issue I see is that you're dividing using integer division. 1 / 27 is equal to 0. 1.0 / 27.0 is equal to 0.037...
If all you want is a stretchable background on your button, check out stretchableImageWithLeftCapWidth:topCapHeight: on UIImage. Create the stretchable image that way, then set it to the background of your button.
I don't know the special behaviour with UIButtons (I'd also suggest to use stretchableImages there as it is a compound view). However, if you want to use contentStretch you could do so on an UIView given your data this was:
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,100)];
view.layer.contents = (id)[[UIImage imageNamed:#"button_image"] CGImage];
view.contentStretch = CGRectMake(13./27., 13./27., 1./27., 1./27.);
This should be enough to have a UIView with a stretchable background.
Use -[UIImage stretchableImageWithLeftCapWidth:topCapHeight:].
I put this in the init method of a subclass of UIView:
// Add errorBackground & errorLabel.
rect.size.height = 26.0f;
errorBackground = [[UIImageView alloc] initWithFrame:rect];
errorBackground.image = [[UIImage imageNamed:#"ErrorBubble.png"]
stretchableImageWithLeftCapWidth:13 topCapHeight:0];
UILabel *errorLabel = [[UILabel alloc] initWithFrame:
CGRectMake(0.0f, 0.0f, rect.size.width, rect.size.height)];
errorLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
errorLabel.backgroundColor = [UIColor clearColor];
errorLabel.textAlignment = UITextAlignmentCenter;
errorLabel.font = [UIFont systemFontOfSize:14.0f];
errorLabel.text = #"1 Failed Passcode Attempt";
errorLabel.textColor = [UIColor whiteColor];
errorLabel.shadowColor = [UIColor blackColor];
errorLabel.shadowOffset = CGSizeMake(0.0f, -1.0f);
[errorBackground addSubview:errorLabel];
[errorLabel release];
[self addSubview:errorBackground];
ErrorBubble.png:
ErrorBubble#2x.png:
Unsatisfying but simple answer:
You can't, until Apple fixes this. IMO it's a long outstanding and very annoying bug.
The UIButton implementation consists of a couple of subviews, and the (internal) background view does not seem to reflect the settings done on the UIButton view.