Disable UITextField keyboard? - iphone

I put a numeric keypad in my app for inputing numbers into a text view, but in order to input numbers I have to click on the text view. Once I do so, the regular keyboard comes up, which I don't want.
How can I disable the keyboard altogether? Any help is greatly appreciated.

The UITextField's inputView property is nil by default, which means the standard keyboard gets displayed.
If you assign it a custom input view, or just a dummy view then the keyboard will not appear, but the blinking cursor will still appear:
UIView* dummyView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
myTextField.inputView = dummyView; // Hide keyboard, but show blinking cursor
If you want to hide both the keyboard and the blinking cursor then use this approach:
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
return NO; // Hide both keyboard and blinking cursor.
}

For Swift 2.x, 3.x, 4.x, 5.x
textField.inputView = UIView()
does the trick

If it's a UITextField, you can set it's enabled property to NO.
If it's a UITextView, you can implement -textViewShouldBeginEditing: in its delegate to return NO, so that it'll never start editing. Or you can subclass it and override -canBecomeFirstResponder to return NO. Or you could take advantage of its editing behavior and put your numeric buttons into a view which you use as the text view's inputView. This is supposed to cause the buttons to be displayed when the text view is edited. That may or may not be what you want.

Depending on how you have your existing buttons working this could break them, but you could prevent the keyboard from showing up setting the textView's editable property to NO
myTextView.editable = NO

I have the same problem when had 2 textfields on the same view. My purpose was to show a default keyboard for one textfield and hide for second and show instead a dropdown list.
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
method simply did not work as I expected for 2 textfields , the only workaround I found was
UIView* dummyView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
myTextField.inputView = dummyView;
myTextField.inputAccessoryView = dummyView;
myTextField.tintColor = myTextField.backgroundColor; //to hide a blinking cursor
This will totally hide the keyboard for a target textField (DropDownList in my case) and show a default one when user switches to the 2nd textfield (Account number on my screenshot)

There is a simple hack to it. Place a empty button
(No Text) above the keyboard and have a action Event assign to it. This will stop keyboard coming up and you can perform any action you want in the handle for the button click

To disable UITextField keyboard:
Go to Main.Storyboard
Click on the UITextField to select it
Show the Attributes inspector
Uncheck the User Interaction Enabled
To disable UITextView keyboard:
Go to Main.Storyboard
Click on the UITextView to select it
Show the Attributes inspector
Uncheck the Editable Behavior

I used the keyboardWillShow Notification and textField.endEditing(true):
lazy var myTextField: UITextField = {
let textField = UITextField()
// ....
return textField
}()
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
}
#objc func keyboardWillShow(_ notification: Notification) {
myTextField.endEditing(true)
// if using a textView >>> myTextView.endEditing(true) <<<
}

private void TxtExpiry_EditingDidBegin(object sender, EventArgs e)
{
((UITextField)sender).ResignFirstResponder();
}
In C# this worked for me, I don't use the storyboard.

In Xcode 8.2 you can do it easily by unchecking state "enabled" option.
Click on the textField you want to be uneditable
Go to attirube inspector on right side
Uncheck "enabled" for State
Or if you want to do it via code. You can simply create an #IBOutlet of this text field, give it a name and then use this variable name in the viewDidLoad func (or any custom one if you intent to) like this (in swift 3.0.1):
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
myTextField.isEditable = false
}

Related

how to make keyboard uppercase? (swift)

I need keyboard to be with CapsLock on (please don't answer how to make text in textField uppercased):
You need to specify .autocapitalizationType for your textField in viewDidLoad or somewhere else during setup of the view like so:
override func viewDidLoad() {
super.viewDidLoad()
textField.autocapitalizationType = .allCharacters
}
Now when your textField becomes active, your keyboard will be on caps.
Here are all the possible options for autocapitalizationType.

Is it possible use different instance of UIMenuController for UITextField in Swift?

According to link we should use a singleton UIMenuController instance which is referred to the editing menu.
The problem is I want to show extra items in different situations. For instance, I want to just show "copy" item when keyboard is up. and show "copy" and "reply" when tapping on a tableview row.
When I add "reply" to the UIMenuController instance it is shown when tapping on UITextField too. therefore, I added these codes:
func textViewDidBeginEditing(_ textView: UITextView) {
var nonReplyMenuItems: [UIMenuItem] = []
if let allMenuItems = UIMenuController.shared.menuItems {
for menuItem in allMenuItems {
if menuItem.title != "reply".localized {
nonReplyMenuItems.append(menuItem)
}
}
}
UIMenuController.shared.menuItems = nonReplyMenuItems
UIMenuController.shared.setMenuVisible(true, animated: true)
}
It fixed the problem in most situations, but not all.
when keyboard is up and tapping on a row in tableview "reply" will be added. Then when I tap on UITextView the reply will be shown there too.
It seems your scenario is like it:
tap on textfield ----> shows copy
tap on tableview ---> shows copy and reply
tab on textfield ----> shows copy and reply (you want only copy shows)
As I know the textViewDidBeginEditing calls when your text filed is not editing and you tap on that; So if you have two textfileds by switching on that method calls every time but when you are switching between a text filed and another action base object your text field is editing and its state has not changed.
When you touch on tableview you must call textfield.resignFirstResponder() so when you tap on text field again the textViewDidBeginEditing calls again, the problem of this is hiding keyboard; The better way I preferÙˆ is adding function to touch down of text field or on gesture to do what you write on textViewDidBeginEditing method

tvOS Focus button in a Subview

I am using AVPlayerController and I have added a subview on top of AVPlayerController. As Soon the subview is displayed I want to shift focus from the player to the Subview and focus the UIButton added on top of that Subivew. I have tried preferredfocusview but its a read-only property and I cannot change it. Can anyone pelase assist. Thanks a lot.
First of all, preferredFocusView is deprecated so you should use preferredFocusEnvironments instead.
It is a computed property, which means you don't assign to it, you override it:
override var preferredFocusEnvironments: [UIFocusEnvironment] {
//if subview exists, return the subview or the button, whichever is focusable
return [subview]
//otherwise use the default implementation of AVPlayerController
return super.preferredFocusEnvironments
}
You should also call self.setNeedsFocusUpdate() and self.updateFocusIfNeeded() to request a focus update when you add the subview.

how to avoid keyboard in textfields

I use a couple of buttons '0123456789.' (and some others) as an alternative for a keyboard. They are connected to (several) texfields. I made them all programmatically, so without storyboard. I also use UITextFieldDelegate. That works as expected, and I can input my text into the textfields.
I use the following code for my buttons:
func textFieldDidBeginEditing(textField: UITextField) {
activeField = textField
}
#IBAction func Pressed(sender: UIButton) {
if (activeField != nil) {
switch sender.tag {
case 0:
activeField!.text = activeField!.text+"0"
case 1:
The problem is that every-time I click in a textfield, the keyboard opens up too. I want to avoid that... since I made an alternative for input with the buttons. How can I get rid of the keyboard when I click in a textfield?
Just return NO from textFieldShouldBeginEditing: from the delegate you mention you are already using.
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.
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if (textField == /* a text field that is using your custom layout */)
return NO;
}
[Source]
Though why don't you just use [textField setKeyboardType:UIKeyboardTypeNumberPad];
You should make your custom keypad the inputView of the textField. It will then be shown instead of the built-in keyboard.
i.e.:
textField.inputView = yourCustomKeypad;
I've made a similar input interface, using custom buttons...why not instead of a UITextField, use a UILabel to display the "8,900"(input).
Then just make the buttons manipulate the UILabel.text.

Right align magnifying glass icon in UISearchBar

In Cocoa-Touch we find a control UISearchBar. I need to customize it so that the search icon (which we click performs the respective action) present in the textfield is right aligned. Normally we find it left aligned. Is it possible to do so? I have done R & D but couldn't find it ...
How can I do it? Are there any good tutorials where we can find it?
Unfortunately the UISearchBar wasn't designed to directly support this. In accomplishing what we want it's likely that we're going to have to use workarounds that compromise visually or functionality wise or write a lot of customising code.
I've outlined a couple of approaches that get close to what we want and may be of use.
Accessing Subviews Approach
The text within a UISearchBar is a UITextField that is a subview of that UISearchBar and is accessible through the usually means i.e. view.subviews.
The magnifying glass search icon is a UIImageView in the leftView property of the UITextField. We can switch it over to the right using the following code:
// The text within a UISearchView is a UITextField that is a subview of that UISearchView.
UITextField *searchField;
for (UIView *subview in self.searchBar.subviews)
{
if ([subview isKindOfClass:[UITextField class]]) {
searchField = (UITextField *)subview;
break;
}
}
// The icon is accessible through the 'leftView' property of the UITextField.
// We set it to the 'rightView' instead.
if (searchField)
{
UIView *searchIcon = searchField.leftView;
if ([searchIcon isKindOfClass:[UIImageView class]]) {
NSLog(#"aye");
}
searchField.rightView = searchIcon;
searchField.leftViewMode = UITextFieldViewModeNever;
searchField.rightViewMode = UITextFieldViewModeAlways;
}
Which gives us the following result:
As you can see the icon overruns the edge of the rounded rectangle and the clear icon has disappeared. In addition, the rightView property was intended for other content such as the search results button and bookmarks button. Putting the search icon here may conflict with this functionality in some way even if you were able to use padding of offsets to position it appropriately.
In the very least you can use this approach to extract the icon as a UIImageView and position it explicitly where you see fit as you would any other view and write custom code to handle tap events etc.
Customizing Appearance Approach
In iOS v5.0 and later, you can customize the appearance of search bars using the methods listed here. The following code makes use of offsets to position the icon and text within the UISearchBar:
[self.searchBar setPositionAdjustment:UIOffsetMake(255, 0) forSearchBarIcon:UISearchBarIconSearch];
[self.searchBar setSearchTextPositionAdjustment:UIOffsetMake(-270, 0)];
On a standard UISearchBar of 320 width it looks like the following:
This would keep all event functionality associated with the icon working as expected but unfortunately the UITextField is confused and despite its width, it only displays a very small portion of its text. If you could find a way to allow the text to display beyond what it believes to be the end of the UITextField, this will probably be your best bet.
My requirement was that the search icon should be on the right, and that it should hide whenever the X icon showed up.
I came up with a similar solution as above, but a bit different and also using Swift 2 and AutoLayout. The basic idea is to hide the left view, create a new view with the magnifying glass image, and use autolayout to pin it to the right. Then use UISearchBarDelegate methods to hide the search icon whenever the searchbar text is not empty.
class CustomSearchView: UIView {
//the magnifying glass we will put on the right
lazy var magnifyingGlass = UIImageView()
#IBOutlet weak var searchBar: UISearchBar!
func commonInit() {
searchBar.delegate = self
searchBar.becomeFirstResponder()
//find the search bar object inside the subview stack
if let searchField = self.searchBar.subviews.firstObject?.subviews.filter(
{($0 as? UITextField) != nil }).firstObject as? UITextField {
//hides the left magnifying glass icon
searchField.leftViewMode = .Never
//add a magnifying glass image to the right image view. this can be anything, but we are just using the system default
//from the old left view
magnifyingGlass.image = (searchField.leftView! as? UIImageView)?.image
//add the new view to the stack
searchField.addSubview(magnifyingGlass)
//use autolayout constraints to pin the view to the right
let views = ["view": magnifyingGlass]
magnifyingGlass.translatesAutoresizingMaskIntoConstraints = false
searchField.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"H:[view(12)]-|", options: [], metrics: nil, views: views))
searchField.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"V:[view]-|", options: [], metrics: nil, views: views))
}
}
//hides whenever text is not empty
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
magnifyingGlass.hidden = searchText != ""
}
}