Randy
Randy

Reputation: 4525

Add text to UItextField without erasing old text

I have an UItextField, and I want to display the content of an array in it. So I tried something like that (and then I realised it obviously wouldn't have worked):

for (NSInteger i=0; i<myArray.count; i++) {
    [self.myTextField setText:myArray[i] ];
}

So, as you may guess, this code just displays the last element of my array in my text field.

My question: is it possible to edit the content of a text field, without erasing the content already present ?

Thanks a lot for your answers !

Upvotes: 0

Views: 612

Answers (8)

Floris M
Floris M

Reputation: 1814

Swift answer:

self.myTextField.text = self.myTextField.text?.stringByAppendingString(" ★")

Upvotes: 0

Hussain Shabbir
Hussain Shabbir

Reputation: 15005

Try with fast enumeration it will be faster:-

for (NSString *str in  myArray)
{
    self.myTextField.text = [self.myTextField.text stringByAppendingString:str];
}

Upvotes: 0

Castro Kitchner
Castro Kitchner

Reputation: 69

There are many ways to do this. One way to do this using your existing method is

for (NSInteger i = 0; i < myArray.count; i++) {

    self.myTextField.text = [NSString stringWithFormat:@"%@ %@", self.myTextField.text, myArray[i]];

}

Upvotes: 1

Shams Ahmed
Shams Ahmed

Reputation: 4513

NSArray has a method called componentsJoinedByString' which returns an NSString object that is the result of interposing a given separator between the elements of the array.

NSString *string = [myArray componentsJoinedByString:@" "];
[self.myTextField setText:string];

Upvotes: 0

Zane Helton
Zane Helton

Reputation: 1052

I didn't debug this so forgive me if it doesn't work.

for (NSInteger i = 0; i < myArray.count; i++) {
    self.myTextField.text = [self.myTextField.text stringByAppendingString:myArray[i]];
}

Upvotes: 0

Undo
Undo

Reputation: 25687

If you just want to append text to the existing text, you can do this:

for (NSInteger i = 0; i < myArray.count; i++) {
    [self.myTextField setText:[self.myTextField.text stringByAppendingString:myArray[i]]];
}

Upvotes: 0

Stonz2
Stonz2

Reputation: 6396

Instead of setting to your field every iteration, append the array contents to a mutable string and set the field to that string at the end. You may need to append spaces or new lines as needed if you want to format it differently.

NSMutableString *arrayContentsString = [[NSMutableString alloc] init];

for (NSInteger i = 0; i < myArray.count; i++) {
    [arrayContentsString appendString:myArray[i]];
}

[self.myTextField setText:arrayContentsString];

Upvotes: 0

CW0007007
CW0007007

Reputation: 5681

Try:

[self.myTextField setText:[[self.myTextField text] stringByAppendingString:myArray[i]]];

Upvotes: 1

Related Questions