Rectangle 27 6

Use following lines of code

NSString *str_test = @"Example ";
NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet];
if([str_test rangeOfCharacterFromSet:whitespaceSet].location!=NSNotFound)
{
    NSLog(@"Found");
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if([string isEqualToString:@" "])
    {
        return NO
    }
    else
    {
        return YES
    }
}

This will find any whitespace (for example also in "A title"). The poster wants to know if the string is only whitespace (for example " ").

iphone - How to know if a UITextField in iOS has blank spaces - Stack ...

iphone ios ipad nsstring uitextfield
Rectangle 27 10

PRE-iOS-8.0 (dated solution)... In your button's action method (toggling between secureTextEntry YES and NO), simply set UITextField's text property to its current text value. Although this may seem redundant and a bit like a hack, this will redraw the cursor in the right position. Here's an example of what your button's action method should look like now...

-(void)toggleButtonPressed:(UIButton*)sender
{
    // Toggle between secure and not-so-secure entry
    self.toggleButton.selected = !self.toggleButton.selected;
    self.textfield.secureTextEntry = !self.toggleButton.selected;

    // * Redundant (but necessary) line *
    [self.textfield setText:self.textfield.text];
}

POST-iOS-8.0... As of iOS 8.0, it appears that UITextField's text setter no longer redraws the cursor when called with a string equal to its current string value. Now, we need to take this a step further and actually change the text value before resetting it again. Replace the above setText: line with something like these lines.

// * Extra redundant (but necessary) lines *
NSString *currentText = self.textfield.text;
[self.textfield setText:@"Arbitrary string..."]; // Change the value
[self.textfield setText:currentText]; // Reset the value

This doesn't work in iOS 8.1.

You're right - it looks like UITextField's iOS 8.0+ text setter now ignores duplicate strings... Thanks @sethfri and other commenters.

This worked great in 9.3 textField.text = textField.text (after toggling secure text entry)

ios - UITextField has trailing whitespace after secureTextEntry toggle...

ios uitextfield
Rectangle 27 11

Here is the hack solution I came up with for a specific layout. This solution is similar to Matt Gallagher solution in that is scrolls a section into view. I am still new to iPhone development, and am not familiar with how the layouts work. Thus, this hack.

My implementation needed to support scrolling when clicking in a field, and also scrolling when the user selects next on the keyboard.

I had a UIView with a height of 775. The controls are spread out basically in groups of 3 over a large space. I ended up with the following IB layout.

UIView -> UIScrollView -> [UI Components]

Here comes the hack

I set the UIScrollView height to 500 units larger then the actual layout (1250). I then created an array with the absolute positions I need to scroll to, and a simple function to get them based on the IB Tag number.

static NSInteger stepRange[] = {
    0, 0, 0, 0, 0, 0, 0, 0, 0, 140, 140, 140, 140, 140, 410
};

NSInteger getScrollPos(NSInteger i) {
    if (i < TXT_FIELD_INDEX_MIN || i > TXT_FIELD_INDEX_MAX) {
        return 0 ;
    return stepRange[i] ;
}

Now all you need to do is use the following two lines of code in textFieldDidBeginEditing and textFieldShouldReturn (the latter one if you are creating a next field navigation)

CGPoint point = CGPointMake(0, getScrollPos(textField.tag)) ;
[self.scrollView setContentOffset:point animated:YES] ;
- (void) textFieldDidBeginEditing:(UITextField *)textField
{
    CGPoint point = CGPointMake(0, getScrollPos(textField.tag)) ;
    [self.scrollView setContentOffset:point animated:YES] ;
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    NSInteger nextTag = textField.tag + 1;
    UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];

    if (nextResponder) {
        [nextResponder becomeFirstResponder];
        CGPoint point = CGPointMake(0, getScrollPos(nextTag)) ;
        [self.scrollView setContentOffset:point animated:YES] ;
    }
    else{
        [textField resignFirstResponder];
    }

    return YES ;
}

This method does not 'scroll back' as other methods do. This was not a requirement. Again this was for a fairly 'tall' UIView, and I did not have days to learn the internal layout engines.

ios - How to make a UITextField move up when keyboard is present? - St...

ios objective-c uitextfield uikeyboard
Rectangle 27 3

You'll want to cast the first and second lines in your function, like this:

func textFieldDidEndEditing(textField: UITextField!){
            var cell: UITableViewCell = textField.superview.superview as UITableViewCell
            var table: UITableView = cell.superview as UITableView
            let textFieldIndexPath = table.indexPathForCell(cell)
}

superview returns a UIView, so you need to cast it to the type of view you expect.

Now it builds correctly but when the simulator runs the "cell as UITableView" the app crashes. Might you guess whats wrong?

It's probably because the cell's superview isn't a UITableView. You'll have to access the tableview differently

Useful. Exactly what I was looking for.

ios - Get indexPath of UITextField in UITableViewCell with Swift - Sta...

ios uitableview swift
Rectangle 27 12

One slightly better way of doing it is to iterate up through the view hierarchy, checking for each superview if it's an UITableViewCell using the class method. That way you are not constrained by the number of superviews between your UITextField and the cell.

Something along the lines of:

UIView *view = field;
while (view && ![view isKindOfClass:[UITableViewCell class]]){ 
    view = view.superview;
}

Really excellent and brilliant ! many thanks, you saved me lot of time. Just don't forget to cast "view" later to "UITableViewCell*" and it works like a charm, and is nicely compact. (But why didn't I think of it all by myself? ;-) )

ios - How to get a UITableViewCell from one of its subviews - Stack Ov...

ios uitableview
Rectangle 27 1

set delegate of UITextField, and over ride, textFieldShouldReturn method, in that method just write following two lines:

[textField resignFirstResponder];
return YES;

that's it. Before writing a code dont forget to set delegate of a UITextField and set Return key type to "Done" from properties window.(command + shift + I).

ios - How to hide the keyboard when i press return key in a UITextFiel...

ios objective-c cocoa-touch delegates
Rectangle 27 2

for(UIView *subView in sb_manSearch.subviews) {
    if([subView conformsToProtocol:@protocol(UITextInputTraits)]) {

        UITextField *t = (UITextField *)subView;
        [t setKeyboardAppearance: UIKeyboardAppearanceAlert];

        t.returnKeyType = UIReturnKeyDone;
        t.delegate = self;
        break;
    }
}

iphone - UISearchBar Keyboard Return Key - Stack Overflow

iphone ios
Rectangle 27 9

I set up a simple example along similar lines. Write some text in a text field, press the button, and it puts the text in a Label in the next View Controller.

It's not very difficult. Create the storyboard layout in the Interface Builder. To make the segue you just control click on the button and drag over to the Second View Controller.

The code for the First View Controller is

import UIKit

class FirstViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!

    // This function is called before the segue
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        // get a reference to the second view controller
        let secondViewController = segue.destinationViewController as! SecondViewController

        // set a variable in the second view controller with the String to pass
        secondViewController.receivedString = textField.text!
    }

}

And the code for the Second View Controller is

import UIKit

class SecondViewController: UIViewController {

    @IBOutlet weak var label: UILabel!

    // This variable will hold the data being passed from the First View Controller
    var receivedString = ""

    override func viewDidLoad() {
        super.viewDidLoad()

        // Used the text from the First View Controller to set the label
        label.text = receivedString
    }

}
  • Hook up the outlets for the UITextField and the UILabel.
  • Set the first and second View Controllers to the appropriate Swift files in IB.

The process to pass the data on to a Third View Controller would be the same.

ios - Passing data between View Controllers using Segue - Stack Overfl...

ios uiviewcontroller segue
Rectangle 27 0

In cellForRowAtIndexPath method add following lines

Create a model class to update the user input for all textfields in different cells

Update text from textfield to your model class in 'updateUserInput' method

  • Your textFieldShouldReturn method should be like this //Mark - UITextField delegates func textFieldShouldReturn(_ textField : UITextField) -> Bool { let returnTypeValue = textField.returnKeyType if returnTypeValue == .done || returnTypeValue == .default { textField.resignFirstResponder() } else if returnTypeValue == .next { let currentRow : Int = textField.tag if (currentRow + 1 < inputKeysArr.count) { self.respondToField(currentRow + 1, errorField: "") } else { textField.resignFirstResponder() } } return true } func respondToField(_ count: Int, errorField : String) { if count < inputKeysArr.count { //WE have more inputs to be made as become first responder let nextIndexPath : IndexPath = IndexPath.init(row: count, section: 0) tableView?.scrollToRow(at: nextIndexPath, at: UITableViewScrollPosition.middle, animated: true) scrollingCompletionClosure = { (weakRef: ViewController) -> Void in } let nonOptionalCell: UITableViewCell = UITableViewCell() let cell: UITableViewCell = (tableView!.cellForRow(at: nextIndexPath)) ?? nonOptionalCell if (cell.isKind(of: TableCell.self)) { let cell : TableCell = cell as! TableCell cell.txtField?.becomeFirstResponder() } } }

ios - Same type textfield in UItableview - Stack Overflow

ios objective-c uitextfield
Rectangle 27 0

First of all declare a variable to identify your active UITextField.

var activeTextField: UITextField
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

Now define these two methods in your controller class.

func keyboardWillShow(_ notification: NSNotification) {

    self.scrollView.isScrollEnabled = true
    var info = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeField = self.activeField {
        if (!aRect.contains(activeField.frame.origin)){
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }
}


func keyboardWillHide(_ notification: NSNotification) {

    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.isScrollEnabled = true
}


func textFieldDidBeginEditing(_ textField: UITextField){

    activeField = textField
}

func textFieldDidEndEditing(_ textField: UITextField){

    activeField = nil
}

ios - Move a view up only when the keyboard covers an input field - St...

ios swift keyboard xcode6
Rectangle 27 0

First of all declare a variable to identify your active UITextField.

var activeTextField: UITextField
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

Now define these two methods in your controller class.

func keyboardWillShow(_ notification: NSNotification) {

    self.scrollView.isScrollEnabled = true
    var info = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeField = self.activeField {
        if (!aRect.contains(activeField.frame.origin)){
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }
}


func keyboardWillHide(_ notification: NSNotification) {

    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.isScrollEnabled = true
}


func textFieldDidBeginEditing(_ textField: UITextField){

    activeField = textField
}

func textFieldDidEndEditing(_ textField: UITextField){

    activeField = nil
}

ios - Move a view up only when the keyboard covers an input field - St...

ios swift keyboard xcode6
Rectangle 27 0

i've read answers and solved my problem by this lines of code:

class ViewController: UIViewController, UITextFieldDelegate {

  @IBOutlet weak var titleField: UITextField!
  @IBOutlet weak var priceField: UITextField!
  @IBOutlet weak var detailsField: UTtextField!

  override func viewDidLoad() {
   super.viewDidLoad()
// Do not to forget to set the delegate otherwise the textFieldShouldReturn(_:)
// won't work and the keyboard will never be hidden.
   priceField.delegate = self
   titleField.delegate = self
   detailsField.delegate = self

   NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow),
 name: NSNotification.Name.UIKeyboardWillShow, object: nil)

   NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide),
 name: NSNotification.Name.UIKeyboardWillHide, object: nil)
  }

   func textFieldShouldReturn(_ textField: UITextField) -> Bool {
      self.view.endEditing(true)
      return false
   }

 func keyboardWillShow(notification: NSNotification) {
   var translation:CGFloat = 0
   if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
     if detailsField.isEditing{
       translation = CGFloat(-keyboardSize.height)
     }else if priceField.isEditing{
       translation = CGFloat(-keyboardSize.height / 3.8)
     }
   }
    UIView.animate(withDuration: 0.2) {
   self.view.transform = CGAffineTransform(translationX: 0, y: translation)
    }
  }


 func keyboardWillHide(notification: NSNotification) {
    UIView.animate(withDuration: 0.2) {
     self.view.transform = CGAffineTransform(translationX: 0, y: 0)
    } 
  }
}

I have a few UITextFields and want the view to move up differently depending on which textField is tapped.

ios - Move view with keyboard using Swift - Stack Overflow

ios swift uikit nsnotificationcenter uikeyboard
Rectangle 27 0

Maybe this is going to be an overkill for what you're asking but the best way I know to do such a thing without using a delegate method is using Reactive Functional Programming, that way it's possible to listen to the events of the UITextField with an Observable object. I have some experience using ReactiveKit more specifically Bond, and with that you only need like one or two lines of code to implement what you need.

ios - How do you intercept a text input event from keyboard in a UITex...

ios swift uitextfield uikit
Rectangle 27 -1

  • New create file UI Test Case and Unit Test Case templates are not much different , ( The former two lines of code Select Unit Test in the test will prompt "Application is not running"Adding "XCUIApplication().launch()" can solve the problem
  • When the test prompted not to find a control (E.g UITextField)Please set the control name \ identity -> accessibility -> Label \ to the same name as the control used in the UITestClass
  • You did not add the test class to the corresponding UI Targets

ios - ‘NSInternalInconsistencyException’ when running UITesting with X...

ios xcode swift xcode7 xcode-ui-testing