简体   繁体   中英

How to update text in a UITextField programmatically in a loop

I am trying to dynamically update the text in a UITextField while in a loop and the text does not show up in real time. When the loop is complete it will display the final value. How do I get the text to display each time it is updated in the loop? I have found many threads on updating in a tableview but this text field is just on the main app. Here is a simple app with a text field and a button.

in ViewController.h #import

@interface ViewController : UIViewController<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *myText;
@property (weak, nonatomic) IBOutlet UIButton *myButton;
- (IBAction)pressMe:(UIButton *)sender;
@end

in ViewController.m #import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize myButton,myText;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    myText.delegate = self;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)pressMe:(UIButton *)sender {

    for (int i=0;i<10;i++){
        NSString *m = [[NSString alloc] initWithFormat:@"%d",i];
        NSLog(@"%@",m);
        [myText setText:m];
        [NSThread sleepForTimeInterval:.05];
    }
}
@end

The texfield delegate is connected to the view controller. This is a simple app to illustrate what I am trying to do. My actual app is trying to display lat lon from the gps to the screen with continual updates. Any help is appreciated.

If your intention is to update the text in the fields with GPS coordinates, I'd suggest setting the text in CLLocationManagerDelegate method locationManager:didUpdateLocations: (assuming you are using CLLocationManager to track user location). This method is called as and when location is updated. No need for GCD here.

Sample Code:

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {

    CLLocation *mostRecentLocation = [locations lastObject];

    latitudeTextField.text = [NSString stringWithFormat:@"%f", mostRecentLocation.coordinate.latitude];
    longitudeTextField.text = [NSString stringWithFormat:@"%f", mostRecentLocation.coordinate.longitude];
}

You should use dispatch_async(dispatch_get_main_queue(), ^{ }); for UI updates in different thread. [textfield setNeedsDisplay] also can work if you are already in main thread

Try This Once..

-(IBAction)btnPress:(id)sender
{

    for (int i=0;i<10;i++){
        NSString *m = [[NSString alloc] initWithFormat:@"%d",i];
        NSLog(@"%@",m);

        [NSThread detachNewThreadSelector:@selector(call:) toTarget:self withObject:m];
        sleep(1);
    }
}

-(void)call:(NSString *)str
{
    _myText.text = str;
}
@interface ViewController ()
{
    NSTimer *timer;
    NSInteger i;
}
@end

- (void)viewDidLoad {
   [super viewDidLoad];

   i=0;       

   timer = [NSTimer scheduledTimerWithTimeInterval:1.0
       target:self
       selector:@selector(targetMethod:)
       userInfo:nil
       repeats:YES];    


   myText.delegate = self;
 }

 - (IBAction)StopUpdate:(UIButton *)sender {
    [timerinvalidate]
 }
 -(void)targetMethod{
    NSString *m = [[NSString alloc] initWithFormat:@"%d",i];
    i++;
    [myText setText:m];
 }
-(IBAction)btnPressed:(id)sender
{
dispatch_queue_t Queue = dispatch_queue_create("",0);
    dispatch_async(Queue, ^{
        for (int i=1 ; i<=10;i++) {
            sleep(1);
            dispatch_async(dispatch_get_main_queue(),^{

                myTxtFld.text = [NSString stringWithFormat:@"%d",i];
            }
            );
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM