Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Changing a word inside a label

How would I change one word in a string by clicking a button without affecting the other words?

Eg I like treehouse To I love treehouse

2 Answers

Alex Hedley
Alex Hedley
16,381 Points
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target 
                                        withString:(NSString *)replacement

NSString *str = @"This is a string";

str = [str stringByReplacingOccurrencesOfString:@"string"
                                     withString:@"duck"];

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple%5Fref/doc/uid/20000154-SW25

http://stackoverflow.com/questions/668228/string-replacement-in-objective-c

Thanks. Can I put this into an IBAction?

Certainly. An IBAction is simply telling Xcode what sort of code will execute on a button press. In a real application, chances are your label will be an IBOutlet associated with a particular view. Then you just link up some code to an IBAction associated to a button to change the text of that label outlet. The Crystal Ball app is an example of this, more or less: you can tap the view, or shake the phone, and a text label appears with a random prediction. Rather than choose a random prediction, you would simply send the stringByReplacingOccurencesOfString message to your text label.

jQuery. Click listener so that when something is clicked, .text($string).

Sorry. This was for an ios application in xcode.