UiTextField changes font while editing in Swift 1.2 & 2.0 - ios

I have a UITextField with a custom font, everything worked fine until Swift update to 1.2 and 2.0. Afterwards, each time I try to edit a text field, it changes its font to a different one that seems a sort of Times New Roman. Does anyone have experience of that?

I came across this same issue and figured out a solution. The problem boils down to setSecureTextEntry changing the font when it is set, and not changing it back when it is unset. In fact, you can never change the font back as long as your UITextField has first responder.
The trick is to resignFirstResponder before you call setSecureTextEntry: and then becomeFirstResponder again. This will work (as of iOS 9.2), but it triggers the keyboard show/hide animation and will cause the screen to "shake". To get around that, you'll need to kill the keyboard animation as well.
Here's my full solution:
- (void)setSecureTextEntry:(BOOL)secureTextEntry {
__weak typeof(self) weakSelf = self;
[UIView performWithoutAnimation:^{
BOOL resumeResponder = NO;
if([[weakSelf textEntryField] isFirstResponder]) {
resumeResponder = YES;
[[weakSelf textEntryField] resignFirstResponder];
}
[[weakSelf textEntryField] setSecureTextEntry:secureTextEntry];
if(resumeResponder) {
[[weakSelf textEntryField] becomeFirstResponder];
}
}];
}
PS: This isn't a Swift bug. It's a UIKit bug. I had the same issue with Objective-C.

I had a weird case of fonts changing its size and font type, when secureTextEntry for an UiTextField was toggled by using a button action.
Had to explicitly manage font for the UiTextField by using these lines of code:
password.font = UIFont(name: "systemFont", size: 14)
password.font = UIFont.systemFontOfSize(14)
Complete Code used in the Show Password Button:
//Function associated with the button for show password option
#IBAction func switchShowPasswordAction(sender: AnyObject) {
if showPassword{
showPassword = false
password.secureTextEntry = !showPassword
}else{
showPassword = true
password.secureTextEntry = !showPassword
}
//Changing font fix
password.font = UIFont(name: "systemFont", size: 14)
password.font = UIFont.systemFontOfSize(14)
}
Post applying this change:

Since I used custom fonts we need to preserve the original font. Create an extension to UITextField:
extension UITextField {
func enablePasswordModeWithShowHide() {
secureTextEntry = false
let showButton = UIButton(type: UIButtonType.System)
showButton.setTitle("HIDE", forState: .Normal)
showButton.titleLabel?.textAlignment = .Right
showButton.sizeToFit()
rightView = showButton
rightViewMode = .Always
showButton.addTarget(self, action: "handleShowHideTapped", forControlEvents: .TouchUpInside)
showButton.tintColor = UIColor.blackColor()
}
func handleShowHideTapped() {
secureTextEntry = !secureTextEntry
let font = self.font
self.font = nil
self.font = font
if let oldText = text {
text = "";
text = oldText;
}
if let button = rightView as? UIButton {
button.setTitle(secureTextEntry ? "SHOW" : "HIDE", forState: .Normal)
button.sizeToFit()
}
}
}
Where it could be implemented like this:
passwordTextField.enablePasswordModeWithShowHide()

All of these answers pretty much work, but I had to use a different solution to achieve the results I needed, considering I'm using a custom font.
You need to make the text field attributed in the storyboard inspector pane for the UITextField, as follows:
Then, in code, you need to manage the toggling of the visibility, setting the attributed text each time, to ensure its properly formatted. I also resignFirstResponder() on the field just to take care of some positioning glitch that I still haven't figured out yet.
func toggleShowPass() {
self.showing = !showing
txtpassword.secureTextEntry = !showing
textFieldPassword.resignFirstResponder()
let string = textFieldPassword.text!
let attrString = NSMutableAttributedString(string: string)
textFieldPassword.addAttribute(NSFontAttributeName, value: UIFont(name: "AvenirNext-Regular", size: 16.0)!, range: NSMakeRange(0, string.characters.count))
textFieldPassword.attributedText = attrString
}

Set defaultTextAttributes with custom font attribute after toggling the secureTextEntry flag
NSDictionary *attrsDictionary =
#{ NSFontAttributeName://customfont};
_passwordtextfield.defaultTextAttributes = attrsDictionary;

I had to apply the following solution with latest Xcode 7.1.1 which actually worked in my case I suspect this issue is of framework.
- (IBAction)btnPasswordShowAction:(id)sender {
self.txtPassword.secureTextEntry = !self.txtPassword.secureTextEntry;
NSString *tmpString = self.txtPassword.text;
self.txtPassword.text = #" ";
self.txtPassword.text = tmpString;
[self.txtPassword setFont:nil];
self.txtPassword.font = [UIFont fontWithName:#"OpenSans-Regular" size:16.0];
}
#pragma mark - Textfield Delegate Methods
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
[self.txtPassword setFont:nil];
self.txtPassword.font = [UIFont fontWithName:#"OpenSans-Regular" size:16.0];
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
[self.txtPassword setFont:nil];
self.txtPassword.font = [UIFont fontWithName:#"OpenSans-Regular" size:16.0];
return YES;
}

Related

Multiple fonts inside a single UITextField

I have a TextField and three buttons which are 40pts above the TextField. These buttons provide the changing of font size of TextField's text when I clicked on any of them for eg first button set font size to 17 second changes it to 20 and third change it to 24. So I add IbAction to all buttons like
- (IBAction)setRegularText:(id)sender {
self.additionalInfo.font = [UIFont systemFontOfSize:20];
}
And according to button. But it will change the previous entered text too. I want the text font to be change only when user selet the option. Previously entered text's font size must not be changed.
You will need to use the attributed string NSAttributedString. With text field it is best to have a delegate and implement the method on changing the characters in range. This will handle all the cases even when the user pasts the text from somewhere else.
So the NSMutableAttributedString has a method to replace the string in range with a mutable attributed string which is perfect for this method. The new string received by the delegate must simply be converted to the attributed one with a currently set font.
Try something like this:
#interface AttributedTextField : NSObject<UITextFieldDelegate>
#property (nonatomic, strong) NSMutableAttributedString *attributedString;
#property (nonatomic, strong) UIFont *currentFont;
#end
#implementation AttributedTextField
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// ensure having a font
UIFont *font = self.currentFont;
if(font == nil) {
font = [UIFont systemFontOfSize:12.0f];
}
// ensure having a base string
if(self.attributedString == nil) {
self.attributedString = [[NSMutableAttributedString alloc] initWithString:#""];
}
// append the new string
[self.attributedString replaceCharactersInRange:range withAttributedString:[[NSMutableAttributedString alloc] initWithString:string attributes:#{NSFontAttributeName: font}]];
textField.attributedText = self.attributedString; // assign the new text which is attributed
return NO; // return false as we are overriding the text
}
#end
set the tag of every button as the font size that button should change.
i-e
self.button1.tag = 17;
self.button2.tag = 20;
self.button3.tag = 24;
and use the tag as font size.
i-e
- (IBAction)setRegularText:(UIButton *)sender {
self.additionalInfo.font = [UIFont systemFontOfSize:sender.tag];
}
You can set different text size in textfield like this way:
- (void)setFontString:(NSString *)setString setFontSize: (double) fontSize {
self.txtAnswer.text = #"";
self.txtAnswer.text = setString;
self.txtAnswer.font = [UIFont systemFontOfSize:fontSize];
}
- (IBAction)btn1Tap:(id)sender {
[self setFontString:#"Good Morning" setFontSize:20.0f];
}
- (IBAction)btn2Tap:(id)sender {
[self setFontString:#"Good Afternoon" setFontSize:15.0f];
}
- (IBAction)btn3Tap:(id)sender {
[self setFontString:#"Good Evening" setFontSize:10.0f];
}

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 attributedPlaceholder has no effect

I'm trying to make the placeholders in my textfields italic, and since my app is targeting iOS 6.0 or newer, decided to use attributedPlaceholder property instead of rolling something more custom. The code goes as follows:
NSString *plString = #"optional";
NSAttributedString *placeholder = [[NSAttributedString alloc] initWithString:plString
attributes:#{NSFontAttributeName : [UIFont fontWithName:#"HelveticaNeue-LightItalic" size:15]}];
for (UITextField *t in myTextfields){
t.placeholder = plString;
t.attributedPlaceholder = placeholder;
}
Yet the styling of the placeholder still is not italic, but the same as regular text, just dimmer. What am I missing to make the NSAttributedString work?
As noted by warren, the styling currently can't be accomplished the way you're trying. A good workaround would be to set up your textfield's font attributes the way you would like your placeholder to look and then change the font of the textfield whenever the user begins typing. It will look like the placeholder and text are different fonts.
You can do this by creating a delegate of the textfield and utilizing shouldChangeCharactersinRange like this:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// If there is text in the text field
if (textField.text.length + (string.length - range.length) > 0) {
// Set textfield font
textField.font = [UIFont fontWithName:#"Font" size:14];
} else {
// Set textfield placeholder font (or so it appears)
textField.font = [UIFont fontWithName:#"PlaceholderFont" size:14];
}
return YES;
}
This is almost certainly a bug. The documentation for the attributedPlaceholder property claims that the string will be drawn using a gray color regardless of the foreground color attribute, but this is not the case: you can set both the foreground and background colors. Unfortunately, the font attribute appears to get stripped out and reverted to the system font.
As a workaround, I recommend overriding drawPlaceholderInRect: and drawing the placeholder yourself. Additionally, you should file a Radar on this and include a minimal sample project that demonstrates the bug.
I just stumbled upon this issue myself. Apparently, the placeholder will take whatever font the textfield is being assigned with. Just set the textfield's font and you are good.
For everything else, like the colour of the placeholder, I'd still go back to attributedPlaceholder
iOS8/9/Swift 2.0 - working example
func colorPlaceholderText(){
var multipleAttributes = [String : NSObject]()
multipleAttributes[NSForegroundColorAttributeName] = UIColor.appColorCYAN()
//OK - comment in if you want background color
//multipleAttributes[NSBackgroundColorAttributeName] = UIColor.yellowColor()
//OK - Adds underline
//multipleAttributes[NSUnderlineStyleAttributeName] = NSUnderlineStyle.StyleDouble.rawValue
let titleString = "Search port/country/vessel..."
let titleAttributedString = NSAttributedString(string: titleString,
attributes: multipleAttributes)
self.textFieldAddSearch.attributedPlaceholder = titleAttributedString
}

UIAppearance not taking effect on UILabels created programmatically

We have extended UILabel to be able to apply standard fonts and colors for all uses of a given label type in our apps. Eg.
#interface UILabelHeadingBold : UILabel
#end
In our AppDelegate, we apply fonts and colors like this
[[UILabelHeadingBold appearance] setTextColor:<some color>];
[[UILabelHeadingBold appearance] setFont:<some font>];
When adding a UILabel in our XIB's, we can now select the class to be of type UILabelHeadingBold, and it works as expected. The label is shown with the correct font and color, as specified in our AppDelegate.
However, if we create a label programmatically, eg.
UILabelHeadingBold *headingLabel = [[UILabelHeadingBold alloc] initWithFrame:CGRectMake(10, 10, 100, 30)];
[self.mainView addSubview:headingLabel];
the UILabel does not get the expected font/color applied. We have to manually apply these attributes.
Is there a way to make UIAppearance take effect on programatically created UI elements, or does it only work when used within XIB's?
From Apple documentation :
To support appearance customization, a class must conform to the
UIAppearanceContainer protocol and relevant accessor methods must be
marked with UI_APPEARANCE_SELECTOR.
For example in UINavigationBar.h, tintColor is marked with UI_APPEARANCE_SELECTOR
#property(nonatomic,retain) UIColor *tintColor UI_APPEARANCE_SELECTOR;
But in UILabel.h you can see that the textColor and font propertys are not marked with UI_APPEARANCE_SELECTOR but somehow it works when added in Interface Builder (following the documentation it shouldn't work at all).
Simple hack that is working for me with no issues is to create a category with a UIAppearance setter that modifies UILabel properties.
Following UIAppearance conventions I created a method:
- (void)setTextAttributes:(NSDictionary *)numberTextAttributes;
{
UIFont *font = [numberTextAttributes objectForKey:UITextAttributeFont];
if (font) {
self.font = font;
}
UIColor *textColor = [numberTextAttributes objectForKey:UITextAttributeTextColor];
if (textColor) {
self.textColor = textColor;
}
UIColor *textShadowColor = [numberTextAttributes objectForKey:UITextAttributeTextShadowColor];
if (textShadowColor) {
self.shadowColor = textShadowColor;
}
NSValue *shadowOffsetValue = [numberTextAttributes objectForKey:UITextAttributeTextShadowOffset];
if (shadowOffsetValue) {
UIOffset shadowOffset = [shadowOffsetValue UIOffsetValue];
self.shadowOffset = CGSizeMake(shadowOffset.horizontal, shadowOffset.vertical);
}
}
In UILabel category:
#interface UILabel (UISS)
- (void)setTextAttributes:(NSDictionary *)numberTextAttributes UI_APPEARANCE_SELECTOR;
#end
I'm still trying to figure out why the original setter does not work.
I was having this exact same issue, but in Swift. A custom UILabel's appearance would work if added from a storyboard, but not if added from code.
Here's a solution I found in Swift that's working for me:
class MyLabel: UILabel { }
extension UILabel {
#objc dynamic var customFont: UIFont! {
get { return self.font }
set { self.font = newValue }
}
#objc dynamic var customColor: UIColor! {
get { return self.textColor }
set { self.textColor = newValue }
}
}
Then add these lines where you configure your app appearance:
MyLabel.appearance().customFont = UIFont.systemFont(ofSize: 20)
MyLabel.appearance().customColor = UIColor.magenta
#robert.wijas solution works great !
For iOS 7 and upwards I had to update the key since the one he used are deprecated for 7+ :
- (void)setTextAttributes:(NSDictionary *)numberTextAttributes;
{
UIFont *font = [numberTextAttributes objectForKey:NSFontAttributeName];
if (font) {
self.font = font;
}
UIColor *textColor = [numberTextAttributes objectForKey:NSForegroundColorAttributeName];
if (textColor) {
self.textColor = textColor;
}
UIColor *textShadowColor = [numberTextAttributes objectForKey:NSShadowAttributeName];
if (textShadowColor) {
self.shadowColor = textShadowColor;
}
NSValue *shadowOffsetValue = [numberTextAttributes objectForKey:NSShadowAttributeName];
if (shadowOffsetValue) {
UIOffset shadowOffset = [shadowOffsetValue UIOffsetValue];
self.shadowOffset = CGSizeMake(shadowOffset.horizontal, shadowOffset.vertical);
}
}
A workaround that I've used is to manually apply the color from the appearance that is set:
let label = UILabel()
label.textColor = UILabel.appearance().textColor
This way you don't need to reference anything new, or explicitly define the color. This also works for context specific coloring:
label.textColor = UILabel.appearance(whenContainedInInstancesOf:[MyView.self]).textColor

Adding the "Clear" Button to an iPhone UITextField

How do you add that little "X" button on the right side of a UITextField that clears the text? I can't find an attribute for adding this sub-control in Interface Builder in the iPhone OS 2.2 SDK.
Note: In Xcode 4.x and later (iPhone 3.0 SDK and later), you can do this in Interface Builder.
This button is a built-in overlay that is provided by the UITextField class, but as of the iOS 2.2 SDK, there isn't any way to set it via Interface Builder. You have to enable it programmatically.
Add this line of code somewhere (viewDidLoad, for example):
Objective-C
myUITextField.clearButtonMode = UITextFieldViewModeWhileEditing;
Swift 5.0
myUITextField.clearButtonMode = .whileEditing
You can also set this directly from Interface Builder under the Attributes Inspector.
Taken from XCode 5.1
Swift 4+:
textField.clearButtonMode = UITextField.ViewMode.whileEditing
or even shorter:
textField.clearButtonMode = .whileEditing
you can add custom clear button and control the size and every thing using this:
UIButton *clearButton = [UIButton buttonWithType:UIButtonTypeCustom];
[clearButton setImage:img forState:UIControlStateNormal];
[clearButton setFrame:frame];
[clearButton addTarget:self action:#selector(clearTextField:) forControlEvents:UIControlEventTouchUpInside];
textField.rightViewMode = UITextFieldViewModeAlways; //can be changed to UITextFieldViewModeNever, UITextFieldViewModeWhileEditing, UITextFieldViewModeUnlessEditing
[textField setRightView:clearButton];
Swift 4 (adapted from Kristopher Johnson's answer)
textfield.clearButtonMode = .always
textfield.clearButtonMode = .whileEditing
textfield.clearButtonMode = .unlessEditing
textfield.clearButtonMode = .never
Objective C :
self.txtUserNameTextfield.myUITextField.clearButtonMode = UITextFieldViewModeWhileEditing;
Swift :
txtUserNameTextfield.clearButtonMode = UITextField.ViewMode.WhileEditing;
this don't work, do like me:
swift:
customTextField.clearButtonMode = UITextField.ViewMode.Always
customTextField.clearsOnBeginEditing = true;
func textFieldShouldClear(textField: UITextField) -> Bool {
return true
}
On Xcode 8 (8A218a):
Swift:
textField.clearButtonMode = UITextField.ViewMode.whileEditing;
The "W" went from capital to non-cap "w".
func clear_btn(box_is : UITextField){
box_is.clearButtonMode = .always
if let clearButton = box_is.value(forKey: "_clearButton") as? UIButton {
let templateImage = clearButton.imageView?.image?.withRenderingMode(.alwaysTemplate)
clearButton.setImage(templateImage, for: .normal)
clearButton.setImage(templateImage, for: .highlighted)
clearButton.tintColor = .white
}
}
Use below lines of code. If rightView is there clear button is not showing.
self.txtField.rightView = nil
self.txtField.rightViewMode = .never
self.txtField.clearButtonMode = UITextField.ViewMode.always
On Xcode Version 8.1 (8B62) it can be done directly in Attributes Inspector. Select the textField and then choose the appropriate option from Clear Button drop down box, which is located in Attributes Inspector.

Resources