Is it possible to align placeholder in the middle of a UITextField? And when we start editing it should it start from left corner of UITextField? I am new to iOS.
Here is the sample code for that.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
txtList.textAlignment = NSTextAlignmentCenter;
}
// This method is called once we click inside the textField
-(void)textFieldDidBeginEditing:(UITextField *)textField{
txtList.textAlignment = NSTextAlignmentLeft;
}
Don't forgot to give delegate of UITextField.
Start by setting textField.textAlignment = NSTextAlignmentCenter. Your best bet is to implement the use of the UITextFieldDelegate protocol to know when the user is tapping inside your text field. Once the user has tapped inside your text field change the property to textField.textAlignment = NSTextAlignmentLeft if you want the alignment to go back to the left. Additionally, using the same protocol, when the user taps out or the focus leaves your text field, set the property back to textField.textAlignment = NSTextAlignmentCenter.
Swift 3.0 ... Swift 5.5
textField.textAlignment = .center
Related
I need to keep the placeholder after the text, when click on the text box i need to clear only the placeholder and able to type characters.
In this Marissa is the name text and (First Name) is placeholder. Once i start editing placeholder need to clear and start editing complete text.
How can i achieve that?
I have found some similar custom textfield in the below URL. If you find this suitable, you can use it.
TUTORIAL / SOURCE
Please refer below code.
Just copy-paste below code in viewdidload()
textfield.attributedPlaceholder = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:#"Yourtext%#",Placehodertext] attributes:#{NSForegroundColorAttributeName: color}];
Assign Delegate of UITextfield to self.
textfield.delegate = self
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
textfield.text = #"Yourtext"
return YES;
}
You can not set place holder along with the text in a textfield.
But there is one alternate for this.
Textfields has something called left view which you can make readOnly view.
Try this :
UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
UILabel *textLabel = [[UILabel alloc] initWithFrame:paddingView.bounds];
textLabel.text = #"Marissa";
[paddingView addSubView:textLabel];
textField.leftView = paddingView;
textField.leftViewMode = UITextFieldViewModeAlways;
Step 1:
Make the text filed attributed form xib and set the "Marisa (First Name)"
and change the color for the (First Name) as grey color .
Step 2:
And in the Textfiled DidBiginEditing method change the textField.text to "Marisa".
This could be achieved in several ways:
Use the attributedText property of UITextField instance to apply a styling for different parts of the text. Here you need to properly define the property each time a user has changed the input by using delegate methods or by observing UIControl Control Events.
If the structure of the text input is fixed and predefined you could use a batch of fields to imitate a more complex/smart field. Here, for example, you need to put two fields beside. One for the last name, second for the first name. Or you can use a combination of UILabel and UITextField if one the part is not editable. Such an approach allows you to configure a separate part of a complex field as you want: different placeholders, fonts, keyboard styles, etc.
Some apps have this nice little white circle with an gray x in there UITextField. How can I add this to an UITextField and delete the text when it is tapped?
To add a button like this, you can use the clearButtonMode property of an UITextField.
The code will be like this:
// Show cancel button never
textField.clearButtonMode = UITextFieldViewModeNever;
// Show cancel button only when you're editing text in textField
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
// Show the cancel button only when you aren't editing the text
textField.clearButtonMode = UITextFieldViewModeUnlessEditing;
// Show always the cancel button
textField.clearButtonMode = UITextFieldViewModeAlways;
Check out the clearButtonMode property.
I was wondering how to display a default prompt in a UITextView. If I wanted the user to type a description in a text view, the UITextView could have "description" printed in it, and when the user starts to type, it disappears.
For UITextField, there is the placeholderText property, which will display a grayed out text that is removed once the user starts typing.
For UITextView, you can use a custom implementation, such as SZTextView, which implements a similar functionality of a placeholder text.
It wont be a wise idea to use a third party uitextview for placeholder property.
Follow these steps and you will achieve what you need-
set- textview.textcolor=[uicolor greycolor];
textview.text=#"Your initial placeholder text";
Now in -textViewShouldBeginEditing write these lines of codes-
if(textview.color==[uicolor greycolor]){
textview.color=[uicolor blackcolor];
textview.text=#"";
}
Cheers.
The below solution from #svmrajesh isn't complete. You still need to implement an auto-delete functionality so the default text deletes as soon as the user selects the textView.
In my implementation I set the text in the UITextView to lightGrayColor initially so that it looks like default text
[textView setTextColor:[UIColor lightGrayColor]];
Then in the header file I implement the UITextViewDelegate.
#interface YourViewController <UITextViewDelegate>
Then I set the UITextView delegate to self.
[textView setDelegate:self];
Then simply I implement the following delegate method which is fired when the user selects the textView to start typing in their text. The first thing it does is to check if the text color is still set to lightGray.
If it is then the default text is still being displayed, so it is deleted and the textColor is set to black. This simple solution works well for me.
-(void)textViewDidBeginEditing:(UITextView *)textView
{
if(textView.textColor == [UIColor lightGrayColor])
{
textView.textColor = [UIColor blackColor];
textView.text = #"";
}
}
Try this....
For UITextView :
UITextView *myUITextView = [[UITextView alloc] init];
myUITextView.delegate = self;
myUITextView.text = #"placeholder text here...";
For UITextField :
UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 150, 200)];
textField.placeholderText = #"Enter your text here";
[self.view addSubview textField];
There is a textField and a button in my view, and if the
textfield is empty I do not want to user can click the button.
When user text something in the textfield, the button will bu
clickable.
How can I do this? Thank you.
for your UITextField, you can set:
[textField addTarget:self action:#selector(editing:) forControlEvents:UIControlEventAllEditingEvents];
Then in your editing: have:
-(void)editing:(UITextField *)sender {
myButton.enabled = ![sender.text isEqualToString:#""];
}
Listen for changes to the text field. As the text changes, update the button's enabled property based on whether there is text or not. Of course you also need to set the button's state at the beginning as well.
// Setup the text field change listener (this can be done in IB if appropriate)
// Put this in viewDidLoad if not using IB.
UITextField *myTextField = ... // a reference to the text field
[myTextField addTarget:self action:#selector(textFieldChangedAction:) forControlEvents:UIControlEventEditingChanged];
// Initialize the button's state (put this in viewDidLoad)
myButton.enabled = myTextField.text.length > 0;
// The method called as the text changes in the text field
- (void)textFieldChangedAction:(UITextField *)sender {
myButton.enabled = sender.text.length > 0;
}
If you want, you can "hide" the button by setting the alpha value of the button to 0 and when the textfield is at least one character long, then set the button's alpha value to 1 to "show" the button. I think this conceptually is easy to do and very presentable to the user.
Set the textfield.delegate to self
Then in delegate that is textfielddidbeginediting
(
Check is textfield is #""
Then disable the button
Else
Enable the button
)
And there is one more. Delegate u can use
Textdidchangecharacters
And in viewdidload first state of the button should be disabled
I am developing an application where user has to write some information. For this purpose I need a UITextField which is multi-line (in general UITextField is a single line).
As I'm Googling I find a answer of using UITextView instead of UITextfield for this purpose.
UITextField is specifically one-line only.
Your Google search is correct, you need to use UITextView instead of UITextField for display and editing of multiline text.
In Interface Builder, add a UITextView where you want it and select the "editable" box. It will be multiline by default.
You can fake a UITextField using UITextView. The problem you'll have is that you lose the place holder functionality.
If you choose to use a UITextView and need the placeholder, do this:
In your viewDidLoad set the color and text to placeholders:
myTxtView.textColor = .lightGray
myTxtView.text = "Type your thoughts here..."
Then make the placeholder disappear when your UITextView is selected:
func textViewDidBeginEditing (textView: UITextView) {
if myTxtView.textColor.textColor == ph_TextColor && myTxtView.isFirstResponder() {
myTxtView.text = nil
myTxtView.textColor = .white
}
}
When the user finishes editing, ensure there's a value. If there isn't, add the placeholder again:
func textViewDidEndEditing (textView: UITextView) {
if myTxtView.text.isEmpty || myTxtView.text == "" {
myTxtView.textColor = .lightGray
myTxtView.text = "Type your thoughts here..."
}
}
Other features you might need to fake:
UITextField's often capitalize every letter, you can add that feature to UITableView:
myTxtView.autocapitalizationType = .words
UITextField's don't usually scroll:
myTxtView.scrollEnabled = false
Ok I did it with some trick ;) First build a UITextField and increased it's size like this :
CGRect frameRect = textField.frame;
frameRect.size.height = 53;
textField.frame = frameRect;
Then build a UITextView exactly in the same area that u made my UITextField, and deleted its background color. Now it looks like that u have a multiple lines TextField !
Besides from the multiple line behaviour, the main difference between UITextView and UITextField is that the UITextView does not propose a placeholder. To bypass this limitation, you can use a UITextView with a "fake placeholder."
See this SO question for details: Placeholder in UITextView.
If you must have a UITextField with 2 lines of text, one option is to add a UILabel as a subview of the UITextField for the second line of text. I have a UITextField in my app that users often do not realize is editable by tapping, and I wanted to add some small subtitle text that says "Tap to Edit" to the UITextField.
CGFloat tapLlblHeight = 10;
UILabel *tapEditLbl = [[UILabel alloc] initWithFrame:CGRectMake(20, textField.frame.size.height - tapLlblHeight - 2, 70, tapLlblHeight)];
tapEditLbl.backgroundColor = [UIColor clearColor];
tapEditLbl.textColor = [UIColor whiteColor];
tapEditLbl.text = #"Tap to Edit";
[textField addSubview:tapEditLbl];
Yes, a UITextView is what you're looking for. You'll have to deal with some things differently (like the return key) but you can add text to it, and it will allow you to scroll up and down if there's too much text inside.
This link has info about making a screen to enter data:
create a data entry screen
'override func viewDidLoad(){
super.viwDidLoad()
YOUR_TEXT_VIEW.textColor = UIColor.gray // YOUR PREFERRED PLACEHOLDER COLOR HERE
YOUR_TEXT_VIEW.text = "YOUR DEFAULT PLACEHOLDER TEXT HERE"
YOUR_TEXT_VIEW.delegate = self
}'
This code block is enough. Please don't forget to set delegate in viewDidLoad or by storyboard just before to use the following extension:
extension YOUR_VIEW_CONTROLLER: UITextViewDelegate {
func textViewDidBeginEditing (_ textView: UITextView) {
if YOUR_TEXT_VIEW.text.isEmpty || YOUR_TEXT_VIEW.text == "YOUR DEFAULT PLACEHOLDER TEXT HERE" {
YOUR_TEXT_VIEW.text = nil
YOUR_TEXT_VIEW.textColor = .red // YOUR PREFERED COLOR HERE
}
}
func textViewDidEndEditing (_ textView: UITextView) {
if YOUR_TEXT_VIEW.text.isEmpty {
YOUR_TEXT_VIEW.textColor = UIColor.gray // YOUR PREFERED PLACEHOLDER COLOR HERE
YOUR_TEXT_VIEW.text = "YOUR DEFAULT PLACEHOLDER TEXT HERE"
}
}
}
use UITextView instead of UITextField
A supplement to h4xxr's answer in the above, an easier way to adjust the height of the UITextField is to select square border style in the attribute inspectors->Text Field. (By default, the border style of a UITextfield is ellipse.)
Reference: Answered Brian in here : How to set UITextField height?
Use textView instead then conform with its delegate, call the textViewDidChange method inside of that method call tableView.beginUpdates() and tableView.endUpdates() and don't forget to set rowHeight and estimatedRowHeight to UITableView.automaticDimension.
There is another option that worked for me:
Subclass UITextField and overwrite:
- (void)drawTextInRect:(CGRect)rect
In this method you can for example:
NSDictionary *attributes = #{ NSFontAttributeName : self.font,
NSForegroundColorAttributeName : self.textColor };
[self.text drawInRect:verticalAlignedRect withAttributes:attributes];
This code will render the text using as many lines as required if the rect has enough space. You could specify any other attribute depending on your needs.
Do not use:
self.defaultTextAttributes
which will force one line text rendering