How to toggle show and hide LeftView/RightView of UITextField? - ios

Currently, I set my textfield with LeftView ( icon ) but I want to toggle show it when click some button.
My code.
let imageIconLeftView = UIImageView(image: UIImage())
view.addSubview(imageIconLeftView)
self.inputTextField.leftView = view
self.inputTextField.leftViewMode = .always
I have a button for toggle it but I have no idea to do this.
func hideIcon() {
/// code for hide textfield's leftView
}
Can someone suggest some idea about it?.

In your hideIcon method, try self.inputTextField.leftView = nil and don't forget to call your hideIcon method.

Related

Swift 4 - How to enable / disable keyboard by using buttons

My tricky problem is :
I've 2 buttons with 2 UITextView.
Like you know, when I push an UITextView, keyboard appear. Well, this is not what I want.
I want to enable / disable the display's keyboard according a specific #IBAction taped.
The scenario is the following:
- First button (Keyboard icon) allow the user to display the keyboard to type something in one of the UITextView, with a FirstResponder init on the top one.
Second button (REC icon) allow the user to speak and display in pre-selected TextView but without displaying keyboard.
I already known that there is :
isUserInteractionEnabled
and
textViewDidBeginEditing
But it doesn't really fit well and/or fix my issue.
Here a screen to be more explicit (don't give a mind about the third green validate button, it's just for the .POST feature) :
Thanks for any help!
If I understand your problem correctly, You don't want the keyboard to appear when user taps on the textField but rather should come up only when user taps on Keyboard button and should dismiss on tapping other button.
All the posted answers mostly focus only on second part of showing keyboard and dismissing them on tapping button. Whats more tricky is preventing keyboard from appearing in when user taps on textField :)
Possible solutions you can try and their cons:
Solution 1:
Try setting textfield isEnabled = false sure this will prevent keyboard from appearing when user taps on textField but guess what Keyboard will not appear even on calling textfield.becomeFirstResponder() ahhh trouble :)
Solution 2:
implementing textFieldShouldBeginEditing of UITextField delegate and returing true or false based on whether used tapped on button or textField itself.
Sure it works but you will need to figure out way to tell textFieldShouldBeginEditing why was it triggered because of button or because of touch on textField again complications.
My Solution:
Use 2 textFields. One disable user interaction forever and use another textField which will never appear to user but will take care of showing keyboard when required.
Enough talk lets code :)
Step 1:
Lets say your textField which appears on screen is called textField
textfield.isEnabled = false
This will ensure whatever you do keyboard will not appear for this keyboard.
Step 2:
Create a temp textField of frame zero (which user can never tap :P )
tempTextField = UITextField(frame: CGRect.zero)
tempTextField.delegate = self
self.view.addSubview(tempTextField)
Step 3:
Now when user taps on show keyboard button, make your temp textField first responder
tempTextField.becomeFirstResponder()
and when user taps on other button resignFirstResponder for tempTextField.
tempTextField.resignFirstResponder()
Step 4:
But wait when user types nothing appears on my textField. Wait simply implement
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == tempTextField {
self.textfield.text = (self.textfield.text ?? "") + string
}
return true
}
EDIT:
You don't really need two textFields, you can achieve the same with a UILabel and UITextField as well. I chose UITextField as I am not sure what are other requirements of yours!
Problem fixed. Hope it helps :)
Something like this should work:
class MyViewController: UIViewController, UITextViewDelegate {
#IBOutlet var yourTextView: UITextView
override func viewDidLoad() {
super.viewDidLoad()
yourTextView.delegate = self
}
#IBAction func showKeyboard(_ sender: UIButton) {
self.yourTextView.becomeFirstResponder()
}
#IBAction func hideKeyboard(_ sender: UIButton) {
self.yourTextView.resignFirstResponder()
}
}
You say
But it's not really working in my case.
Why?
You can disable the textfields interaction with (swift 3):
textField.isUserInteractionEnabled = false
Next, when you click on the keyboard button you can reenable the interaction so when the user click on one of the textfield the keyboard opens.
On the keyboard dismiss (you can see the UIKeyboardWillHideNotification callback notification) you can set the interaction to false.
function to dismiss KeyBoard when button is clicked:
#IBAction func hideKeyboard() {
textView.resignFirstResponder()
}
function to get keyboard to show up:
#IBAction func showKeyboard() {
textView.becomeFirstResponder()
}
Just copy and paste simple code for you accessory button embedded with keypad
func addKeyboardToolbar() {
let ViewForDoneButtonOnKeyboard = UIToolbar()
ViewForDoneButtonOnKeyboard.sizeToFit()
let button = UIButton.init(type: .custom)
button.setImage(UIImage.init(named: "login-logo"), for: UIControlState.normal)
button.addTarget(self, action:#selector(doneBtnfromKeyboardClicked), for:.touchUpInside)
button.frame = CGRect.init(x: 0, y: 0, width:UIScreen.main.bounds.width, height: 30) //CGRectMake(0, 0, 30, 30)
let barButton = UIBarButtonItem.init(customView: button)
ViewForDoneButtonOnKeyboard.items = [barButton]
postTextView.inputAccessoryView = ViewForDoneButtonOnKeyboard
}
#IBAction func doneBtnfromKeyboardClicked (sender: Any) {
self.contentView.endEditing(true)
}

Hide cursor on UITextView - Swift

I have an app that have user feedback feature. I have done the view as shown in the image.
Feedback view that I made
Message area is using UITextView.
What I want to do now is when user finished editing the textView, then they click other places such as the star rating or any area besides textview, it will hide the cursor on the textview but it will keep the written text at the same time.
Can anyone help me with this? Thank you.
You can make the tint color transparent to hide the cursor.
textView.tintColor = UIColor.clearColor()
In Swift 3:
textView.tintColor = UIColor.clear
Update for Swift 3.x:
textField.tintColor = .clear
Try this:
1) Add a tap gesture recogniser to your view in an appropriate place (viewDidLoad for example)
let tapRecognizer = UITapGestureRecognizer(target: self, action: "hideKeyboard")
view.addGestureRecognizer(tapRecognizer)
2) Then you need to add hideKeyboard method. Example implementation
func hideKeyboard() {
view.endEditing(true)
}
That should do it :)

How do I activate an inputView using a UIButton in Swift?

I am attempting to have a UIDatePicker come up as a keyboard when the user hits a UIButton. I was able to get it to work with a textfield, but I don't like how the cursor is visible and the user could enter in any text if they had an external keyboard. Here is my code:
#IBAction func dateFieldStart(sender: UITextField) {
var datePickerStartView : UIDatePicker = UIDatePicker()
datePickerStartView.datePickerMode = UIDatePickerMode.Time
sender.inputView = datePickerStartView // error when sender is UIButton
}
I tried changing the sender to UIButton but it gave this error on the line that is marked above:
Cannot assign to 'inputView' in 'sender'
I have tried researching it and no one else seems to have had a problem with it. Anyone know how to trigger a UIDatePicker inputView using a UIButton or anything that might work better that the user cannot type into? Thanks!
This is years after the original question, but for anyone who may be looking for solution to this you can subclass UIButton and provide a getter and setter for the inputView property. Be sure to call becomeFirstResponder in the setter and override canBecomeFirstResponder. For example:
class MyButton: UIButton {
var myView: UIView? = UIView()
var toolBarView: UIView? = UIView()
override var inputView: UIView? {
get {
myView
}
set {
myView = newValue
becomeFirstResponder()
}
}
override var inputAccessoryView: UIView? {
get {
toolBarView
}
set {
toolBarView = newValue
}
}
override var canBecomeFirstResponder: Bool {
true
}
}
let tempInput = UITextField( frame:CGRect.zero )
tempInput.inputView = self.myPickerView // Your picker
self.view.addSubview( tempInput )
tempInput.becomeFirstResponder()
It's a good idea to keep a reference to tempInput so you can clean-up on close
I wanted to do the same thing, I ended up just overlaying a UITextField over the button and using the inputView of that instead.
Tip: set tintColor of the UITextField to UIColor.clearColor() to hide the cursor.
You can create a view for the picker off screen view and move it on screen when you need it. Here's another post on this.

How do we highlight or change the color of a button after it is pressed in swift Xcode 6?

I am having a problem in Swift. I want to change the color of a button when I press it. I am actually making a Quiz in which there are four options and I want to change the color to red if the answer is wrong or change the color to green if the answer is correct. Can somebody help me out with this please?
You can use bool for that like shown below:
var currectAnswer = Bool()
change this Boolean into another function if answer is correct set it as true and if answer is wrong then set it to false.
After that you can set this action for that button:
#IBAction func btnPressed(sender: UIButton) {
if currectAnswer {
sender.backgroundColor = UIColor.greenColor()
} else if !currectAnswer {
sender.backgroundColor = UIColor.redColor()
}
}
Hope It will help.
If you want to change the color of the button text,you could try this way:
yourButton.setTitleColor(UIColor.redColor(), forState: .Normal)
If you want to change the background color of the button,try this code:
yourButton.backgroundColor = .greenColor()

Remove clear button in UISearchBar

I want to remove the clear button (gray x) from the UISearchBar. I tried to do it like described in this answer, but it doesn't work.
I translated the Objective-C code from the answer and the comment below to following Swift code:
for subview in searchBar.subviews {
configureSearchBarView(subview as UIView)
}
func configureSearchBarView(view: UIView) {
for subview in view.subviews {
self.configureSearchBarView(subview as UIView)
}
if subview.conformsToProtocol(UITextInputTraits) {
var clearView = view as UITextField
clearView.clearButtonMode = UITextFieldViewMode.Never
}
}
Unfortunatly this doesn't remove the clear button.
Another answer suggests to work with appearanceWhenContainedIn, but this method doesn't seem to be implemented in Swift.
Any ideas?
Swift
I found a better way that completely removes the button, using clearButtonMode = .never
let searchBarStyle = searchBar.value(forKey: "searchField") as? UITextField
searchBarStyle?.clearButtonMode = .never
Swift 5
Tested on iOS 13
As I pointed out in another answer, this is the one liner working for me to make it disappear completely:
searchBar.searchTextField.clearButtonMode = .never
However you may also set it to .whileEditing if you only want it displayed when the user is typing and then make it disappear when the search bar loses focus.
I found a solution. It is possible to exchange the clear button with a custom image:
UISearchBar.appearance().setImage(UIImage(named: "emptyImg"), forSearchBarIcon: UISearchBarIcon.Clear, state: UIControlState.Normal)
UISearchBar.appearance().setImage(UIImage(named: "emptyImg"), forSearchBarIcon: UISearchBarIcon.Clear, state: UIControlState.Highlighted)
emptyImg is an png that contains one white pixel. Found in this answer

Resources