Need to get placeholder text of UITextField - ios

Is it possible to get the placeholder value of UITextField, which is designed in storyboard?
I need to validate the form which is having more textfields, so instead of giving static value, I want to give placeholder string of particular textfield as alert message.

Use the placeholder property:
textField.placeholder

For placeholder first you should create IBOUTLET for textfield and then do:
if let str = textfiled.placeholder {
if !str.isEmpty {
//do something
}
}

The UITextField class has a placeholder property. To reference the UITextField in code, you'll need to create an outlet for it in your view controller.
If you named the outlet myTextField, you could reference the placeholder like this:
let placeholder = self.myTextField.placeholder

Its work ...
For getting placeholder text you need to wire up your textfield with its IBOutlet object like,
#IBOutlet var txtField : UITextField?
Now you set Placeholder Statically or dynamically
self.txtField!.attributedPlaceholder = NSAttributedString(string:"Good", attributes:[NSForegroundColorAttributeName: UIColor.grayColor()])
After that anywhere you can simply get its placeholder text and compare or validate ur textfield like
if((self.txtField!.placeholder! as NSString).isEqualToString("Good"))
{
// Do here Whatever you want
}
else if(self.txtField!.placeholder!.isEmpty == true)
{
// check its empty or not
}

Simply write like below code,
if((self.myTextFiled!.placeholder! as NSString).isEqualToString("AnyString"))
{
// your code here
}

Related

How to observe text change in UITextField using RxSwift?

I want to observe any change of the UITextField.text property using RxSwift.
I trying to use rx.text property, but it called only when I set text property like this: textField.text = "", but not working when I typing text.
Also I tried to use rx.observe(String.self, "text"), but it gives the same result.
How can I observe any change of the text in UITextField?
To observe any change of the text in UITextField you can create extension for Reactive class:
public extension Reactive where Base: UITextField {
public var textChange: Observable<String?> {
return Observable.merge(self.base.rx.observe(String.self, "text"),
self.base.rx.controlEvent(.editingChanged).withLatestFrom(self.base.rx.text))
}
}

Use localized strings in storyboard

I'm pretty new to iOS development and I was asking my self if it is possible to use localized strings from my "Localizable.strings" file directly into the storyboard.
For example in Android you can do it from the XML file like this:
android:text="#string/notConnected"
I understood that you can make a localized version of the storyboard, but having different strings files and different storyboards looks pretty ugly to me.
So is it possible to have only strings files and use what I need into the storyboard? Preferably without setting it from code?
EDIT:
This is practically what I want to do:
So is this possible? Is there a legit way to call a string from there like in Android?
I think being able to localise Strings in the storyboard is of significant advantage. I don't agree with #elk_cloner that hooking up IBOutlets for every UILabel is the way forward.
One way of getting it to work is using an #IBInspectable property on a UILabel subclass:
class LocalisableLabel: UILabel {
#IBInspectable var localisedKey: String? {
didSet {
guard let key = localisedKey else { return }
text = NSLocalizedString(key, comment: "")
}
}
}
In the storyboard set the custom class:
In the attributes inspector the localisedKey field will appear and you can just add your key here.
That's it!
EDIT:
You can localise UIButtons the same way, BUT if the text in the storyboard's title field differs from the localised String (which it will in other languages) the setting of the title will animate.
To fix this, put the setTitle in a performWithoutAnimation block:
class LocalisableButton: UIButton {
#IBInspectable var localisedKey: String? {
didSet {
guard let key = localisedKey else { return }
UIView.performWithoutAnimation {
setTitle(key.localized, for: .normal)
layoutIfNeeded()
}
}
}
}
In addition to Leon's answer, you can get rid of the need for an explicit subclass by using an extension:
extension UILabel {
#IBInspectable var localizableText: String? {
get { return text }
set(value) { text = NSLocalizedString(value!, comment: "") }
}
}
According to your requirement it's not possible but
You don't need different storyboards for localization
Suppose you want to localize a label string.
Draw and outlet and change text using
mylabel.text = nsLocalizedString("THIS_IS_MY_STRING",nil);
Of course in your localization file there will be a line.You must have different files for different language.Suppose you have a file for english and there must be a line.
"THIS_IS_MY_STRING" = "This is my string";
When you compile your app, that function will use mapping to localize your app.
Edit:
If you want detail information please have a look at these tutorials
internationalization-tutorial-for-ios-2014
and ios-localization-tutorial
There are some online script(e.g localize.py) which will help you to automatically search all of your code and find out nslocalizedString function and make lines in your localizableString files. like this.
"THIS_IS_MY_STRING" = "THIS_IS_MY_STRING"
and later on you just have to write actual string there. :)
Make a button class and set #IBInspectable attribute to the button class
class Button: UIButton {
#IBInspectable public var referenceText: String = "" {
didSet {
self.setTitle(NSLocalizedString(referenceText, comment: ""), for: .normal)
}
}
}
Then in the storyboard you can set referenceText
The button text will be "Sign In"
Another possible way is to localize the storyboard and simply change the values for labels and buttons directly on the .string file.
First select the storyboard, and click on localize:
Then you'll be able to select the languages you want.
This way you'll be able to continue developing on your language of choice and simply edit the .string file that is generated
for button
extension UIButton {
#IBInspectable var localizableText: String? {
get { return titleLabel?.text }
set(value)
{
setTitle(NSLocalizedString(value!, comment: ""), for: .normal)
}}}

How to unclear UITextField secure text entry in Swift?

When I use default Security text Entry in UITextField in Swift Language after type type text once UITextField.
Once loss focus from UITextField after try to edit Secure text then UITextField is first reset and after it start put new text in UITextField.
How to edit old Secure Text without Storing data into Any Kind of String object
I'd suggest to create a custom UITextField class and override become​First​Responder() method do add your desired functionality:
You can override this method in your custom responders to update your
object's state or perform some action such as highlighting the
selection. If you override this method, you must call super at some
point in your implementation.
The custom Class should be similar to:
class CustomSecureTextField: UITextField {
override func becomeFirstResponder() -> Bool {
super.becomeFirstResponder()
if !isSecureTextEntry { return true }
if let currentText = text { insertText(currentText) }
return true
}
}
The logic of the implementation of becomeFirstResponder as follows:
By default, the secured-entry text field clears the inserted text when it is become first responder text, so what's happening in CustomSecureTextField that if the text field is secured-entry, it will re-insert the current inserted text -after clearing it-, but you have to make sure that the text field input is secured (that's the purpose of adding if !isSecureTextEntry { return true }) or the text will be duplicated (re-inserted) each time the text field becomes first responder.
Output:
Note that both of text fields are types of CustomSecureTextField:
This answer helped me to figure out this problem.
textField.isSecureTextEntry = true
following property not gonna work if you make testField isSecureTextEntrysecure property makes true .
textField.clearsOnBeginEditing = false
There is an issue with the #Ahmd F solution when you simply tap on the field it will automatically add the text to the field I have resolved that in the below code thanks
override open func becomeFirstResponder() -> Bool {
super.becomeFirstResponder()
if !isSecureTextEntry { return true}
if let currrentText = text {
self.text = ""
insertText(currrentText)
}
return true
}

Xcode How read numbers on a Text View (or label?)

this is my first post.
I'm new in the Xcode Word.
At the moment I'm working to a simple application and I need to read a number from a box and after a lot of calculations write the result in an other text view or label.
I need how to read a numbers or a string from a box after writing (text view, label or other).
Thank you very much for your answers
if you are sure that your textfield will accept only numbers, one of the possible ways could be:
yourTextField.keyboardType = UIKeyboardType.decimalPad
in this way, when the user will tap on the textField, you may use the numeric keypad.
At this point your viewController must implement UItextFieldDelegate
yourTextField.delegate = self
and then use the method, called when textfield loses focus:
func textFieldDidEndEditing(_ textField: UITextField) {
var valueInserted : Float = NSString(string: textField.text!).floatValue
}
Drag a UITextView inside the scene (in the storyboard)
Create an outlet between the UITextView and ViewController.swift
in ViewController.swift you will have something like this:
#IBOutlet weak var myTextView:UITextView!
You must also get a reference for your label
#IBOutlet weak var myLabel:UILabel!
you can now access to the content(input) of your textView by checking the text property:
var input = myTextView.text
This will be a string, that you can try to convert to an Int. Once you have a result to display, set the label text:
myLabel.text = result

Check UIButton already exists or not in Swift

I found Objective-C coding for this topic. But the problem is that most of the classes and functions in Objective-C is deprecated in swift programming language.
I am using a UIButton inside a UITableView with flagForAction[Boolean Value]. So what i want to achieve is that if the UIButton is created once , there is no need to recreate it. So for that i need to check whether the UIButton already exists or not. Somebody suggested me the concept of tag for this, applying a particular tag to this UIButton and checking that is exist on the view or not. But i don't know how to do that.
Setting a tag:
myButton.tag = 1234 // some unique value, probably better to define as an enum or constant
Retrieving a view by tag (likely in cellForRowAtIndexPath):
if let myButton = tableviewCell.viewWithTag(1234) { // change tableviewCell for whatever your tableview cell variable name is
// myButton already existed
} else {
// TableviewCell doesn't contain a myButton, so create one here and set the tag as above
}
in swift 2.0
for view in myview.subviews {
if let btn : UIButton = view as? UIButton {
// access button here, either tag or title etc..
}
}
I am using view as example. You can also identify a button with accessibilityIdentifier property of the button, if you dont want to use tag proprerty of button.
For example :
var button = UIButton(frame: CGRectMake(0, 0, 100, 44))
button.accessibilityIdentifier = "button 1"
self.view.addSubview(button)
Here, i created a button with accessibilityIdentifier "button 1"
While creating the next button, i will check in the subview if it contains the button with accessibilityIdentifier "button 1", as below
var subviews : NSArray = self.view.subviews
for button : AnyObject in subviews{
if(button .isKindOfClass(UIButton)){
if(button.accessibilityIdentifier == "button 1"){
println("Button Already Exists")
}else{
println("Create new button")
}
}
}

Resources