How to initialize a UITextView programmatically? - iphone

How can I initialize a UITextView that is nice and pretty. I have the line:
textView = [[UITextView alloc] initWithFrame:CGRectMake(150, 150, 100, 100)];
but I'd like to make it look nice and I do not know the functions or the syntax to do so. I'd like it to have word wraping and I'd like the corners to be rounded. Also, how can I make it so that the keyboard goes away if the user presses "Return" on the keyboard. And I'd like to make it say "Done" instead of "Return"

You should check the documentation. This is all in there. Specifically:
you can't set the border, you can only do that for a UITextField
you'll need to set your delegate and implement -textViewDidChange: to check for returns
you can set textView.returnKeyType to UIReturnKeyDone to get the Done button.
You might want to consider using a UITextField, as that object's delegate has a very convenient -textFieldShouldReturn: method, and you can, as I said, set its border.

check out the UItextInputTraits protocol that is linked from the UITextView documentation.
All of these properties can be found there, and others.
EX:
textView.returnKeyType = UIReturnKeyTypeDone;

To make the border look close to a UITextField, you can add the following lines.
[textView.layer setBorderColor:[[[UIColor grayColor] colorWithAlphaComponent:0.5] CGColor]];
[textView.layer setBorderWidth:1.0];
textView.layer.cornerRadius = 3;
textView.clipsToBounds = YES;
To release the keyboard by pressing 'Done'('Return') button, you can override the following protocol (UITextViewDelegate) method.
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if ([text isEqualToString:#"\n"]) {
[textView resignFirstResponder];
return NO;
}
return YES;
}

Related

how to set uitextfield bordercolor in iphone application [duplicate]

This question already has answers here:
UITextField border color
(9 answers)
Closed 9 years ago.
how to set uitextfield and UITextView border color programmatically , when we enter or edit in textfield and textview.
I used this code, but doesn't change the border color for the UITextView.
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
textField.layer.borderColor=[[UIColor cyanColor] CGColor];
}
Don't Forget : #Import <QuartzCore/QuartzCore.h>
Working Code :
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
textField.layer.cornerRadius=8.0f;
textField.layer.masksToBounds=YES;
textField.layer.borderColor=[[UIColor redColor]CGColor];
textField.layer.borderWidth= 1.0f;
return YES;
}
For give Border and Color Of UITextField.
Add #import "QuartzCore/QuartzCore.h" fram work.
textField.layer.borderColor = [UIColor lightGrayColor].CGColor; // set color as you want.
textField.layer.borderWidth = 1.0; // set borderWidth as you want.
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
declares if the user is allowed to edit a text field. Change the method to:
- (void)textFieldDidBeginEditing:(UITextField *)textField {
textField.layer.borderColor=[[UIColor cyanColor] CGColor];
}
When you edit a text field, there are a lot of methods that seem really similar. You are trying to use-textFieldShouldBeginEditing:. According to the documentation, textFieldShouldBeginEditing, "Asks the delegate if editing should begin in the specified text field." The usage is, "When the user performs an action that would normally initiate an editing session, the text field calls this method first to see if editing should actually proceed. In most circumstances, you would simply return YES from this method to allow editing to proceed." This is not what you wan't to do.
Instead you should use -textFieldDidBeginEditing:. This method, "Tells the delegate that editing began for the specified text field." It, "notifies the delegate that the specified text field just became the first responder. You can use this method to update your delegate’s state information. For example, you might use this method to show overlay views that should be visible while editing."
This means your code should change from:
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
textField.layer.borderColor=[[UIColor cyanColor] CGColor];
}
to
-(BOOL)textFieldDidBeginEditing:(UITextField *)textField {
textField.layer.borderColor=[[UIColor cyanColor] CGColor];
}
You can read more about the UITextFieldDelegate methods in the docs at http://developer.apple.com/library/ios/#documentation/uikit/reference/UITextFieldDelegate_Protocol/UITextFieldDelegate/UITextFieldDelegate.html

changing the frame of UITextView as I am typing

I can use the code below to set the size of the textView frame, to approximately match the textView's content (the typed text) when I press a button or whatnot. How would I call this whenever a new character is typed, so that the frame would grow or shrink interactively?
- (IBAction)doneEditingText:(id)sender {
[myTextView resignFirstResponder];
[myTextView setFrame:CGRectMake(myTextView.frame.origin.x, myTextView.frame.origin.y, myTextView.contentSize.width, myTextView.contentSize.height)];
}
Thanks for reading
EDIT :
Implement UITextView delegate in .h file this:
#interface ViewController : UIViewController<UITextViewDelegate>
If yourTextView added from xib then bind delegate with fileowner otherwise in ViewDidLoad add this line:
yourTextView.delegate = self;
Use textView's delegate for your requirement:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
CGSize maximumSize = CGSizeMake(280,999); //specify width of textView and maximum height for text to fit in width of textView
CGSize txtSize = [textView.text sizeWithFont:[UIFont fontWithName:#"Arial" size:16] constrainedToSize:maximumSize lineBreakMode:UILineBreakModeCharacterWrap]; //calulate size of text by specifying font here
//Add UIViewAnimation here if needed
[textView setFrame:CGRectMake(textView.frame.origin.x,textView.frame.origin.y,txtSize.width+10,txtSize.height+10)]; // change accordingly
return YES;
}
You can use something like this repo on GIT which has the almost same functionality that you want-
https://github.com/HansPinckaers/GrowingTextView
it's similar like message app in iPhone.
I just got done implementing this. The problem with the current (as of posting this answer) accepted answer is that the delegate method:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
exposes the textView before the change the user has typed/inserted/deleted is commited. therefore, the resizing you would be achieving would be one character late. UITextView does inherit from a UIScrollView so the text wouldn't clip off of screen but it could lead to some awkward behavior.
My Solution is to use two delegate methods to achieve the resizing effect correctly.
Expanding the UITextView before the character the user typed hits the screen:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
NSMutableString *tempString = [NSMutableString stringWithString:textView.text];
[tempString replaceCharactersInRange:range withString:text];
//If we are adding to the length of the string (We might need to expand)
if([tempString length]>textView.text.length)
{
//Create a temporaryTextView which has all of the characteristics of your original textView
UITextView *tempTextView = [[UITextView alloc] initWithFrame:CGRectZero];
tempTextView.font = _inputFont;
tempTextView.contentInset = textView.contentInset;
[tempTextView setText:tempString];
//Change this to respect whatever width constraint you are trying to achieve.
CGSize theSize = [tempTextView sizeThatFits:CGSizeMake(192, CGFLOAT_MAX)];
if(theSize.height!=textView.frame.size.height)
{
textView.frame = CGRectMake(115, 310, 192,theSize.height);
return YES;
}
else
{
return YES;
}
}
else
{
return YES;
}
}
And Shrinking after the user has deleted/shrunk the amount of text in the UITextView the character
-(void)textViewDidChange:(UITextView *)textView
{
//We enter this method AFTER the edit has been drawn to the screen, therefore check to see if we should shrink.
if([textView sizeThatFits:CGSizeMake(192, CGFLOAT_MAX)].height!=textView.frame.size.height)
{
//change this to reflect the constraints of your UITextView
textView.frame = CGRectMake(115, 310, 192,[textView sizeThatFits:CGSizeMake(192, CGFLOAT_MAX)].height);
}
}

UItextView arabic text aligned to right

Using my custom arabic keyboard on UItextView inputView, I m filling my textView with the arabic text but cannot get the written text align to right....Need help to align text to right.
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView{
if(showCustomKeyboard==NO){
[textView resignFirstResponder];
textView.inputView=nil;
[textView becomeFirstResponder];
return YES;
}
else{
[textView resignFirstResponder];
if(customKeyboard==nil){
customKeyboard=[[CustomKeyboard alloc] initWithFrame:CGRectMake(0, 264, 320, 216)];
[customKeyboard setDelegate:self];
}
if([[UIApplication sharedApplication] respondsToSelector:#selector(inputView)]){
if (textView.inputView == nil) {
textView.inputView = customKeyboard;
[textView becomeFirstResponder];
}
}
self.customKeyboard.currentField=textView;
[textView becomeFirstResponder];
}
return YES;
}
You can set the writing direction of a UITextView using the setBaseWritingDirection selector:
UITextView *someTextView = [[UITextView] alloc] init];
[someTextView setBaseWritingDirection:UITextWritingDirectionLeftToRight forRange:[someTextView textRangeFromPosition:[someTextView beginningOfDocument] toPosition:[someTextView endOfDocument]]];
The code is a little tricky because UITextView supports having different parts of the text with different writing directions. In my case, I used [someTextView textRangeFromPosition:[someTextView beginningOfDocument] toPosition:[someTextView endOfDocument]] to select the full text range of the UITextView. You can adjust that part if your needs are different.
You may also want to check whether the text in your UITextView is LTR to RTL. You can do that with this:
if ([someTextView baseWritingDirectionForPosition:[someTextView beginningOfDocument] inDirection:UITextStorageDirectionForward] == UITextWritingDirectionLeftToRight) {
// do something...
}
Note that I specified the start of the text using [someTextView beginningOfDocument] and searched forward using UITextStorageDirectionForward. Your needs might differ.
If you subclass UITextView replace all these code samples with "self" and not "someTextView", of course.
I recommend reading about the UITextInput protocol, to which UITextView conforms, at http://developer.apple.com/library/ios/#documentation/uikit/reference/UITextInput_Protocol/Reference/Reference.html.
Warning about using the textAlignment property in iOS 5.1 or earlier: if you use it with this approach together with setting the base writing direction, you will have issues because RTL text when aligned left in a UITextView actually aligns to the right visually. Setting text with an RTL writing direction to align right will align it to the left of the UITextView.
Try textAlignment property.
textView.textAlignment = UITextAlignmentRight;
Take a look at UITextView Class Reference.
EDIT: Maybe CATextLayer can help you, someone suggests to use this class to customize text, but I've never used it personally...
Otherwise, you can force your textView to reverse your input in UITextFieldDelegate method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
The text field calls this method whenever the user types a new character in the text field or deletes an existing character.
Here you can replace your input with a new NSString where you put the characters from right to left.
Hope this makes sense...
Ah... Do not forget to set
textView.textAlignment = UITextAlignmentRight;
to move your prompt on the right.
Try this code:
yourtextview.textAlignment = UITextAlignmentRight;
Hope this helps you.
Something which no one mentioned here or on any other post is that make sure you have not called sizeToFit for TextView. It simple aligns the textView (not text) to the left which gives the illusion that text is left to right instead of right to left.
If you are creating UI from Storyboard, the set constraint to Lead or Trailing space and value of First Item will be Respect Language Direction
in swift you can use this code
textView.makeTextWritingDirectionRightToLeft(true)

Set alpha transparency on accessoryView

I am trying to add a UIView as an accessoryView to a UITextField, but the alpha property doesnt seem to be respected.
Here is my current code.
self.keyboardAccView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 480.0)];
[self.keyboardAccView setBackgroundColor:[UIColor lightGrayColor]];
[self.keyboardAccView setOpaque:NO];
[self.keyboardAccView setAlpha:0.0];
UITapGestureRecognizer *hideKeyboardTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(hideKeyboard:)];
[self.keyboardAccView addGestureRecognizer:hideKeyboardTap];
[hideKeyboardTap release], hideKeyboardTap=nil;
The alpha value doesnt seem to matter. No matter what I set it to, the accessoryView is always set to no transparency.
What I'm trying to accomplish is show a transparent view above the keyboard that will dismiss the keyboard anytime the user taps away from the keyboard. If there is a better/proper way to do this that I am completely missing, I'm all ears as well.
EDIT *
I know I could just use [UIColor clearColor] as the backgroundColor but I more want to know why the alpha setting isnt honored, in case I truly did want to have a semi-transparent accessoryView
yes - there is a better way to do it! :)
I personally do it like this - I change my ViewController.xib class (UIView to UIControl) and then I create a simple IBAction which resigns first responder whenever is the UIControl tapped.
The method should look like this:
- (IBAction)hideKeyboard {
[textField resignFirstResponder];
}
That's it :)

UITextView highlightedTextColor or similar option?

I have a custom UITableViewCell with a UILabel and a UITextView in it.
I want the text for both of these to appear white when the user highlights the UITableViewCell. It's obviously very simple to set the highlightedTextColor of the UILabel, but the UITextView doesn't seem to have any similar type of property. Am I going to have to manually change the color of the UITextView whenever the cell becomes highlighted/unhighlighted or is there an easier way of accomplishing this?
Thanks!
Found it and it was a lot easier than I thought. Just need to use the UITableViewCell setHighlighted method.
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
[super setHighlighted:highlighted animated:animated];
if (highlighted) {
[self.myTextView setTextColor:[UIColor whiteColor]];
} else {
[self.myTextView setTextColor:[UIColor blackColor]];
}
}
The solution posted by the author is half right for my situation. Need to keep in mind that the following events happen:
press down --> setHighlighted:YES animated: is called
press up --> setHighlighted:NO animated is called
set selection --> setSelected:YES animated is called
Knowing this, and depending on how you want the TableCell to look when highighted vs when selected will determine if you need to implement setHighlighted:animated:, setSelected:animated: or both methods.
For the look I want, I need to implement both methods.