Custom UITextField delegate set to self initiates infinite loop - ios

I am writing iPhone App in which I need custom UITextField class. For my text fields I need indent, image inside before the text and max characters. For this reason I created custom class based on UITextField. All my text fields will be based on this new class. I use Google and searched Stackoverflow and I find that in cases like mine I have to use self.delegate = self; during the init so I don't need to implement methods like textFieldShouldBeginEditing or textFieldShouldEndEditing inside my View Controller class. All my text fields will be created in storyboard so initWithCoder. As a result I receive infinite loop and App crash (I use simulator at this moment) after typing 1, 2 or 3 symbols. It is interesting that for numeric keyboard or password keyboard there is no such issue. Also if I type symbols on my Mac keyboard instead on the simulator there is no problem. I tried to debug but during the crash it jumps directly into loop and exist with error.
How to overcome this problem?
P.S. I asked question when I receive infinite loop and there was comments that self.delegate = self; can cause such loop, but I see that this statement is widely used. May be I did not do this correctly, but I can not figure out how to make reusable class out of UITextField.
EDIT:
Here is my code:
On inti I initialize and set border color:
- (id)initWithCoder:(NSCoder *)aDecoder{
self = [super initWithCoder:aDecoder];
if (self) {
self.layer.borderColor=[[UIColor blackColor] CGColor];
self.delegate = self;
}
return self;
}
When I start edit I change border color and set indent (indent set will be moved in property setter):
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
// Change border of text field that is editing to orange
textField.layer.masksToBounds=YES;
textField.layer.borderColor=[[UIColor orangeColor] CGColor];
textField.layer.borderWidth= 1.0f;
UIView *spacerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _leftIndent, 10)];
[self setLeftViewMode:UITextFieldViewModeAlways];
[self setLeftView:spacerView];
return YES;
}
On finish editing I return back color:
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
// Change border of text field that is edited to black
textField.layer.masksToBounds=YES;
textField.layer.borderColor=[[UIColor blackColor] CGColor];
textField.layer.borderWidth= 1.0f;
return YES;
}
And on value change I check max characters:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
// Restrict number of symbols in text field to "maxSymbols"
NSUInteger oldLength = [textField.text length];
NSUInteger replacementLength = [string length];
NSUInteger rangeLength = range.length;
NSUInteger newLength = oldLength - rangeLength + replacementLength;
BOOL returnKey = [string rangeOfString: #"\n"].location != NSNotFound;
return newLength <= (int)_maxSymbols || returnKey;
}

I don't know if this can be actual answer, but I have work around which is the answer of my next question How properly subclass UITextField in iOS? (from justafinger). I don't make assignment self.delegate = self; in my custom control, but I have methods that are called from delegates in view controller.
I hope this can help people with problem like mine.

Related

Set text(with emojis, special chars, links) in UILabel, and link should be clickable

In one of my application, there is API called and get data from server. In that there is text - which contains emojis, special characters, URLs, etc.
Not In my UITableViewCell, I have Simple UILabel and set text to label.
Till now everything is working fine.
But now I want that URLs in UILabel should be tappable, so when we click on URL and it should be open in Safari.
Note : As text is coming from server, so I don't know position of URL and there will be multiple URL as well.
What to do for that ? I have searched but didn't find solution.
I needed this kind of linked text for another project last month. I created a custom UITableViewCell with a UITextView object in the cell, subclassed to a custom UITextView subclass. I just made a quick demo project and put it up on git for you now. Feel free to use it.
github.com/fareast555/MPC_LinkedTextView
The basic secret sauce for using text links is the NSLinkAttributeName attribute in the mutable text, and telling the system to handle links.
- (void)updateTextViewWithFullText:(NSString *)fullText linkTriggerText:(NSString *)triggerText linkURLString:(NSString *)urlString
{
//Create a mutable string based on the full text
NSMutableAttributedString *mutableString = [[NSMutableAttributedString alloc]initWithString:fullText attributes:nil];
//Add the link attribute across the range of the target text
[mutableString addAttribute:NSLinkAttributeName value:urlString range:[fullText rangeOfString:triggerText]];
//Add any other font or color bling as needed
[mutableString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:18 weight:UIFontWeightMedium] range:NSMakeRange(0, [fullText length])];
//Set the mutable text to the textfield
[self setAttributedText: mutableString];
}
#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction
{
return YES;
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
return NO;
}
And for textviews, you'll find it easier to use auto layout if you turn off scrolling.
#pragma mark - Configure
- (void)_configureTextView
{
self.delegate = self;
[self setEditable:NO];
[self setSelectable:YES];
[self setScrollEnabled:NO];
[self setUserInteractionEnabled:YES];
[self setDataDetectorTypes:UIDataDetectorTypeLink];
self.scrollIndicatorInsets = UIEdgeInsetsZero;
}

How to change text in UITextView and UITextField

I need to edit my UITextView and when I make these changes I need them to reflect that in my UITextFields. Currently i can use the code below to move whatever text i write into the first UITextField is there a simple way to move each line to a separate UITextField?
Like the image, except the 1, 2 and 3 going to a different UITextField.
-(IBAction)print:(id)sender {
NSString *texto = [[NSString alloc] initWithFormat:#"%# %#",[myTextField text],[myTextView text]];
[myTextField setText:texto];
[myTextView setText:#""];
[myTextView resignFirstResponder];
}
Really, I need to figure this out. Any help will be appreciated.
Have your view controller conform to the UITextViewDelegate protocol.
Next, set the delegate property of your text view to your view controller.
Then, implement - (void)textViewDidChange:(UITextView *)textView, along these lines:
- (void)textViewDidChange:(UITextView *)textView
{
// Set the text for your text fields.
//
// (I'm assuming your code for determining the text to put in the
// text fields works as you intend, so I'm just copying it here.)
NSLayoutManager *layoutManager = [textView layoutManager];
unsigned numberOfLines, index, numberOfGlyphs = [layoutManager numberOfGlyphs];
NSRange lineRange;
for (numberOfLines = 0, index = 0; index < numberOfGlyphs; numberOfLines++)
{
(void) [layoutManager lineFragmentRectForGlyphAtIndex:index
effectiveRange:&lineRange];
index = NSMaxRange(lineRange);
NSString *lineText = [textView.text substringWithRange:lineRange];
[yourArray addObject:lineText];
}
textField1.text=yourArray[0];
textField2.text=yourArray[1];
textField3.text=yourArray[2];
textField4.text=yourArray[3];
textField5.text=yourArray[4];
textField6.text=yourArray[5];
textField7.text=yourArray[6];
}

Why does the font on iOS textfields changes upon altering secureTextEntry programatically? [duplicate]

I’m using a custom font in a UITextField, which has secureTextEntry turned on. When I’m typing in the cell, I see the bullets in my chosen font, but when the field loses focus, those bullets revert to the system standard font. If I tap the field again, they change back to my font, and so on.
Is there a way I can ensure that they continue to display the custom font’s bullets, even when the field is out of focus?
A subclass that works this issue around. Create an arbitrary UITextField, then set the secure property to YES (via KVC in IB).
Actually it implements a comment suggested by lukech. When textfield ends editing, it switches to an arbitrary textfield, then set a bulk of dots into, and some hack in text accessor to always get the actual text the field holds.
#interface SecureTextFieldWithCustomFont : UITextField
#property (nonatomic) BOOL secure;
#property (nonatomic, strong) NSString *actualText;
#end
#implementation SecureTextFieldWithCustomFont
-(void)awakeFromNib
{
[super awakeFromNib];
if (self.secureTextEntry)
{
// Listen for changes.
[self addTarget:self action:#selector(editingDidBegin) forControlEvents:UIControlEventEditingDidBegin];
[self addTarget:self action:#selector(editingDidChange) forControlEvents:UIControlEventEditingChanged];
[self addTarget:self action:#selector(editingDidFinish) forControlEvents:UIControlEventEditingDidEnd];
}
}
-(NSString*)text
{
if (self.editing || self.secure == NO)
{ return [super text]; }
else
{ return self.actualText; }
}
-(void)editingDidBegin
{
self.secureTextEntry = YES;
self.text = self.actualText;
}
-(void)editingDidChange
{ self.actualText = self.text; }
-(void)editingDidFinish
{
self.secureTextEntry = NO;
self.actualText = self.text;
self.text = [self dotPlaceholder];
}
-(NSString*)dotPlaceholder
{
int index = 0;
NSMutableString *dots = #"".mutableCopy;
while (index < self.text.length)
{ [dots appendString:#"•"]; index++; }
return dots;
}
#end
May be augmented to work with non NIB instantiations, handling default values, etc, but you probably get the idea.
For those having trouble with losing custom fonts when toggling secureTextEntry, I found a work-around (I'm using the iOS 8.4 SDK). I was trying to make a toggle for showing/hiding a password in a UITextField. Every time I'd toggle secureTextEntry = NO my custom font got borked, and only the last character showed the correct font. Something funky is definitely going on with this, but here's my solution:
-(void)showPassword {
[self.textField resignFirstResponder];
self.textField.secureTextEntry = NO;
}
First responder needs to be resigned for some reason. You don't seem to need to resign the first responder when setting secureTextEntry to YES, only when setting to NO.
The actual problem appears to be that the editing view (UITextField does not draw its own text while editing) uses bullets (U+2022) to draw redacted characters, while UITextField uses black circles (U+25CF). I suppose that in the default fonts, these characters look the same.
Here's an alternate workaround for anyone interested, which uses a custom text field subclass, but doesn't require juggling the text property or other special configuration. IMO, this keeps things relatively clean.
#interface MyTextField : UITextField
#end
#implementation MyTextField
- (void)drawTextInRect:(CGRect)rect
{
if (self.isSecureTextEntry)
{
NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
paragraphStyle.alignment = self.textAlignment;
NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
[attributes setValue:self.font forKey:NSFontAttributeName];
[attributes setValue:self.textColor forKey:NSForegroundColorAttributeName];
[attributes setValue:paragraphStyle forKey:NSParagraphStyleAttributeName];
CGSize textSize = [self.text sizeWithAttributes:attributes];
rect = CGRectInset(rect, 0, (CGRectGetHeight(rect) - textSize.height) * 0.5);
rect.origin.y = floorf(rect.origin.y);
NSMutableString *redactedText = [NSMutableString new];
while (redactedText.length < self.text.length)
{
[redactedText appendString:#"\u2022"];
}
[redactedText drawInRect:rect withAttributes:attributes];
}
else
{
[super drawTextInRect:rect];
}
}
#end
While this is an iOS bug (and new in iOS 7, I should add), I do have another way to work around it that one might find acceptable. The functionality is still slightly degraded but not by much.
Basically, the idea is to set the font to the default font family/style whenever the field has something entered in it; but when nothing is entered, set it to your custom font. (The font size can be left alone, as it's the family/style, not the size, that is buggy.) Trap every change of the field's value and set the font accordingly at that time. Then the faint "hint" text when nothing is entered has the font that you want (custom); but when anything is entered (whether you are editing or not) will use default (Helvetica). Since bullets are bullets, this should look fine.
The one downside is that the characters, as you type before being replaced by bullets, will use default font (Helvetica). That's only for a split second per character though. If that is acceptable, then this solution works.
I found a trick for this issue.
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
if ([textField tag]== TAG_PASS || [textField tag]== TAG_CPASS)
{
// To fix password dot size
if ([[textField text] isEqualToString:#"" ])
{
[textField setText:#" "];
[textField resignFirstResponder];
[textField becomeFirstResponder];
[textField setText:#""];
}
}
}
[passWordTextField resignFirstResponder];
passWordTextField.secureTextEntry = !passWordTextField.secureTextEntry;
[passWordTextField becomeFirstResponder];
This is the fastest way to solve this bug!
iOS is acting a bit strange when it comes to custom fonts. Try removing "Adjust to Fit" for that textfield. If that doesn't work, I'm guessing that what bothering you is the size increase of the font.
A simple solution for that would be:
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
if(textField.secureTextEntry)
{
[textField setFont:[UIFont fontWithName:#"Helvetica-Bold" size:10.0]];
}
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
if(textField.secureTextEntry)
{
[textField setFont:[UIFont fontWithName:#"Helvetica-Bold" size:10.0]];
}
}
You'll need to play with the size a bit in order for it to look like there is no size change when loosing focus on the UITextField.
If you have a major spacing problem between characters like in the edited question, the simplest (and a bit ugly) solution would be to create a Bullet image that matches the above size & spacing and matches the amount of characters entered by the user that will appear when the user leaves the UITextField.
A secureTextEntry text field can be avoided altogether:
NSString *pin = #"";
BOOL pasting = FALSE;
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(!pasting) {
pin = [pin stringByReplacingCharactersInRange:range withString:string];
// Bail out when deleting a character
if([string length] == 0) {
return YES;
}
pasting = TRUE;
[textField paste:#"●"];
return NO;
} else {
pasting = FALSE;
return YES;
}
}
I recommend to resignFirstResponder before you change scureTextEntry and then becomeFirstResponder again as it is posted here: https://stackoverflow.com/a/34777286/1151916
Swift 5 and iOS 14 is around but isSecureTextEntry set to true for custom font still displays the wrong size bullets, although the actual leading letter is of the correct size.
None of the solutions from stack overflow has worked for me except a hacky workaround of setting the font to the system font when password is in secure mode.
if textField.isSecureTextEntry {
self.textField.font = UIFont.systemFont(ofSize: 17)
} else {
self.textField.font = UIFont(name: "Roboto-Regular", size: 17)
}

UITextField secureTextEntry bullets with a custom font?

I’m using a custom font in a UITextField, which has secureTextEntry turned on. When I’m typing in the cell, I see the bullets in my chosen font, but when the field loses focus, those bullets revert to the system standard font. If I tap the field again, they change back to my font, and so on.
Is there a way I can ensure that they continue to display the custom font’s bullets, even when the field is out of focus?
A subclass that works this issue around. Create an arbitrary UITextField, then set the secure property to YES (via KVC in IB).
Actually it implements a comment suggested by lukech. When textfield ends editing, it switches to an arbitrary textfield, then set a bulk of dots into, and some hack in text accessor to always get the actual text the field holds.
#interface SecureTextFieldWithCustomFont : UITextField
#property (nonatomic) BOOL secure;
#property (nonatomic, strong) NSString *actualText;
#end
#implementation SecureTextFieldWithCustomFont
-(void)awakeFromNib
{
[super awakeFromNib];
if (self.secureTextEntry)
{
// Listen for changes.
[self addTarget:self action:#selector(editingDidBegin) forControlEvents:UIControlEventEditingDidBegin];
[self addTarget:self action:#selector(editingDidChange) forControlEvents:UIControlEventEditingChanged];
[self addTarget:self action:#selector(editingDidFinish) forControlEvents:UIControlEventEditingDidEnd];
}
}
-(NSString*)text
{
if (self.editing || self.secure == NO)
{ return [super text]; }
else
{ return self.actualText; }
}
-(void)editingDidBegin
{
self.secureTextEntry = YES;
self.text = self.actualText;
}
-(void)editingDidChange
{ self.actualText = self.text; }
-(void)editingDidFinish
{
self.secureTextEntry = NO;
self.actualText = self.text;
self.text = [self dotPlaceholder];
}
-(NSString*)dotPlaceholder
{
int index = 0;
NSMutableString *dots = #"".mutableCopy;
while (index < self.text.length)
{ [dots appendString:#"•"]; index++; }
return dots;
}
#end
May be augmented to work with non NIB instantiations, handling default values, etc, but you probably get the idea.
For those having trouble with losing custom fonts when toggling secureTextEntry, I found a work-around (I'm using the iOS 8.4 SDK). I was trying to make a toggle for showing/hiding a password in a UITextField. Every time I'd toggle secureTextEntry = NO my custom font got borked, and only the last character showed the correct font. Something funky is definitely going on with this, but here's my solution:
-(void)showPassword {
[self.textField resignFirstResponder];
self.textField.secureTextEntry = NO;
}
First responder needs to be resigned for some reason. You don't seem to need to resign the first responder when setting secureTextEntry to YES, only when setting to NO.
The actual problem appears to be that the editing view (UITextField does not draw its own text while editing) uses bullets (U+2022) to draw redacted characters, while UITextField uses black circles (U+25CF). I suppose that in the default fonts, these characters look the same.
Here's an alternate workaround for anyone interested, which uses a custom text field subclass, but doesn't require juggling the text property or other special configuration. IMO, this keeps things relatively clean.
#interface MyTextField : UITextField
#end
#implementation MyTextField
- (void)drawTextInRect:(CGRect)rect
{
if (self.isSecureTextEntry)
{
NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
paragraphStyle.alignment = self.textAlignment;
NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
[attributes setValue:self.font forKey:NSFontAttributeName];
[attributes setValue:self.textColor forKey:NSForegroundColorAttributeName];
[attributes setValue:paragraphStyle forKey:NSParagraphStyleAttributeName];
CGSize textSize = [self.text sizeWithAttributes:attributes];
rect = CGRectInset(rect, 0, (CGRectGetHeight(rect) - textSize.height) * 0.5);
rect.origin.y = floorf(rect.origin.y);
NSMutableString *redactedText = [NSMutableString new];
while (redactedText.length < self.text.length)
{
[redactedText appendString:#"\u2022"];
}
[redactedText drawInRect:rect withAttributes:attributes];
}
else
{
[super drawTextInRect:rect];
}
}
#end
While this is an iOS bug (and new in iOS 7, I should add), I do have another way to work around it that one might find acceptable. The functionality is still slightly degraded but not by much.
Basically, the idea is to set the font to the default font family/style whenever the field has something entered in it; but when nothing is entered, set it to your custom font. (The font size can be left alone, as it's the family/style, not the size, that is buggy.) Trap every change of the field's value and set the font accordingly at that time. Then the faint "hint" text when nothing is entered has the font that you want (custom); but when anything is entered (whether you are editing or not) will use default (Helvetica). Since bullets are bullets, this should look fine.
The one downside is that the characters, as you type before being replaced by bullets, will use default font (Helvetica). That's only for a split second per character though. If that is acceptable, then this solution works.
I found a trick for this issue.
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
if ([textField tag]== TAG_PASS || [textField tag]== TAG_CPASS)
{
// To fix password dot size
if ([[textField text] isEqualToString:#"" ])
{
[textField setText:#" "];
[textField resignFirstResponder];
[textField becomeFirstResponder];
[textField setText:#""];
}
}
}
[passWordTextField resignFirstResponder];
passWordTextField.secureTextEntry = !passWordTextField.secureTextEntry;
[passWordTextField becomeFirstResponder];
This is the fastest way to solve this bug!
iOS is acting a bit strange when it comes to custom fonts. Try removing "Adjust to Fit" for that textfield. If that doesn't work, I'm guessing that what bothering you is the size increase of the font.
A simple solution for that would be:
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
if(textField.secureTextEntry)
{
[textField setFont:[UIFont fontWithName:#"Helvetica-Bold" size:10.0]];
}
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
if(textField.secureTextEntry)
{
[textField setFont:[UIFont fontWithName:#"Helvetica-Bold" size:10.0]];
}
}
You'll need to play with the size a bit in order for it to look like there is no size change when loosing focus on the UITextField.
If you have a major spacing problem between characters like in the edited question, the simplest (and a bit ugly) solution would be to create a Bullet image that matches the above size & spacing and matches the amount of characters entered by the user that will appear when the user leaves the UITextField.
A secureTextEntry text field can be avoided altogether:
NSString *pin = #"";
BOOL pasting = FALSE;
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(!pasting) {
pin = [pin stringByReplacingCharactersInRange:range withString:string];
// Bail out when deleting a character
if([string length] == 0) {
return YES;
}
pasting = TRUE;
[textField paste:#"●"];
return NO;
} else {
pasting = FALSE;
return YES;
}
}
I recommend to resignFirstResponder before you change scureTextEntry and then becomeFirstResponder again as it is posted here: https://stackoverflow.com/a/34777286/1151916
Swift 5 and iOS 14 is around but isSecureTextEntry set to true for custom font still displays the wrong size bullets, although the actual leading letter is of the correct size.
None of the solutions from stack overflow has worked for me except a hacky workaround of setting the font to the system font when password is in secure mode.
if textField.isSecureTextEntry {
self.textField.font = UIFont.systemFont(ofSize: 17)
} else {
self.textField.font = UIFont(name: "Roboto-Regular", size: 17)
}

Hide the cursor of a UITextField

I am using a UITextField with a UIPickerView for its inputView, so that when the user taps the text field, a picker is summoned for them to select an option from.
Nearly everything works, but I have one problem: the cursor still flashes in the text field when it is active, which is ugly and inappropriate, since the user is not expected to type into the field and is not presented with a keyboard. I know I could hackily solve this by setting editing to NO on the text field and tracking touches on it, or by replacing it with a custom-styled button, and summoning the picker via code. However, I want to use the UITextFieldDelegate methods for all the event handling on the text field and hacks such as replacing the text field with a button do not permit this approach.
How can I simply hide the cursor on the UITextField instead?
Simply subclass UITextField and override caretRectForPosition
- (CGRect)caretRectForPosition:(UITextPosition *)position
{
return CGRectZero;
}
As of iOS 7 you can now just set the tintColor = [UIColor clearColor] on the textField and the caret will disappear.
You can just clear the textfield's tintColor
self.textField.tintColor = [UIColor clearColor];
Swift 3.0
self.textField.tintColor = .clear
You might also want to stop the user from selecting, copying or pasting any text so that the only text input comes from the picker view.
- (CGRect) caretRectForPosition:(UITextPosition*) position
{
return CGRectZero;
}
- (NSArray *)selectionRectsForRange:(UITextRange *)range
{
return nil;
}
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
if (action == #selector(copy:) || action == #selector(selectAll:) || action == #selector(paste:))
{
returnNO;
}
return [super canPerformAction:action withSender:sender];
}
http://b2cloud.com.au/tutorial/disabling-the-caret-and-text-entry-in-uitextfields/
Check out the property selectedTextRange of the protocol UITextInput, to which the class UITextField conforms. Few! That's a lesson in object-oriented programing right there.
Hide Caret
To hide the caret, nil out the text field's selected text range.
textField.selectedTextRange = nil; // hides caret
Unhide Caret
Here are two ways to unhide the caret.
Set the text field's selected text range to the end of the document.
UITextPosition *end = textField.endOfDocument;
textField.selectedTextRange = [textField textRangeFromPosition:end
toPosition:end];
To keep the caret in the same spot, first, store the text field's selected text range to an instance variable.
_textFieldSelectedTextRange = textField.selectedTextRange;
textField.selectedTextRange = nil; // hides caret
Then, when you want to unhide the caret, simply set the text field's selected text range back to what it was originally:
textField.selectedTextRange = _textFieldSelectedTextRange;
_textFieldLastSelectedTextRange = nil;
Swift 5 version of Net's post
override func caretRect(for position: UITextPosition) -> CGRect {
return .zero
}
override func selectionRects(for range: UITextRange) -> [UITextSelectionRect] {
return []
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return false
}
Answer provided by the OP, copied from the question body to help clean up the ever growing tail of unanswered questions.
I found another solution: subclass UIButton and override these methods
- (UIView *)inputView {
return inputView_;
}
- (void)setInputView:(UIView *)anInputView {
if (inputView_ != anInputView) {
[inputView_ release];
inputView_ = [anInputView retain];
}
}
- (BOOL)canBecomeFirstResponder {
return YES;
}
Now the button, as a UIResponder, have a similar behavior than UITextField and an implementation pretty straightforward.
set the tintColor to Clear Color
textfield.tintColor = [UIColor clearColor];
and you can also set from the interface builder
If you want to hide cursor, you can easily use this! It worked for me..
[[textField valueForKey:#"textInputTraits"] setValue:[UIColor clearColor] forKey:#"insertionPointColor"]
Answer provided by the OP, copied from the question body to help clean up the ever growing tail of unanswered questions.
I think I have the correct solution but If it can be improved will be welcome :) Well, I made a subclass of UITextField and overriden the method that returns the CGRect for the bounds
-(CGRect)textRectForBounds:(CGRect)bounds {
return CGRectZero;
}
The problem? The text doesn't show because the rect is zero. But I added an UILabel as a subview of the control and overridden the setText method so, as we enter a text as usual, the text field text is nil and is the label which shows the text
- (void)setText:(NSString *)aText {
[super setText:nil];
if (aText == nil) {
textLabel_.text = nil;
}
if (![aText isEqualToString:#""]) {
textLabel_.text = aText;
}
}
With this the thing works as expected. Have you know any way to improve it?
To both disable cursor and menu I use subclass with these 2 methods:
- (CGRect)caretRectForPosition:(UITextPosition *)position {
return CGRectZero;
}
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
[UIMenuController sharedMenuController].menuVisible = NO;
self.selectedTextRange = nil;
return NO;
}
I simply subclass UITextField, and override layoutSubviews as follows:
- (void)layoutSubviews
{
[super layoutSubviews];
for (UIView *v in self.subviews)
{
if ([[[v class] description] rangeOfString:#"UITextSelectionView"].location != NSNotFound)
{
v.hidden = YES;
}
}
}
It's a dirty hack, and may fail in the future (at which point the cursor will be visible again - your app won't crash), but it works.
If you like cleaner = less code, use the interface builder:
(Attributes inspector, view section.)
In my case, overriding the caret rect wasn't enough. On iOS 15, the caret didn't appear, effectively, but the selection handles did.
Solved it with: override var canBecomeFirstResponder: Bool { return false } on the UITextView subclass.
You can add a BOOL cursorless property to UITextField in a category via associated objects.
#interface UITextField (Cursorless)
#property (nonatomic, assign) BOOL cursorless;
#end
Then use method swizzling to swizzle caretRectForPosition: with a method that toggles between CGRectZero and its default value using cursorless.
This leads to a simple interface via a drop-in category. This is demonstrated in the following files.
Simply drop them in and get the benefit of this simple interface
UITextField category:
https://github.com/rexmas/RexDK/blob/master/RexDK/UI/UITextField%2BRXCursorless.h
https://github.com/rexmas/RexDK/blob/master/RexDK/UI/UITextField%2BRXCursorless.m
Method Swizzling:
https://github.com/rexmas/RexDK/blob/master/RexDK/Foundation/NSObject%2BRXRuntimeAdditions.h
https://github.com/rexmas/RexDK/blob/master/RexDK/Foundation/NSObject%2BRXRuntimeAdditions.m

Resources