Problem setting Value for UILabel (iPhone SDK)

2019-08-06 08:03发布

问题:

I'm reasonably new at the iPhone SDK, so please forgive me if this answer's ridiculously obvious.

I have a ViewController connected to a .xib file (they are called FirstViewController)

I also have a custom class called MyCustomClass. In this class, I have a method like this:

- (void)setTheText {
    [myLabel setText:@"foo"];
}

I want to call this method to set the text in a label in FirstViewController.xib

So far, I have done this:

Dragged in an "Object" into Interface Builder, and set the class to: MyCustomClass Connected up the IBOutlet 'myLabel' from MyCustomClass to a UILabel in the view.

However, when I run the program, and press the button to set the label (which is in FirstViewController.m), something like:

- (IBAction)doSomething:(id)sender {
   MyCustomClass *customClass = [MyCustomClass alloc] init];
   [customClass setTheText];
}

This doesn't set though. NSLog(@"%@",[myLabel text]); returns (null)

Xcode shows no errors or warnings, what could be wrong?

Thanks,

Michael

Additional Info:

Interface to MyCustomClass.h:

#import <UIKit/UIKit.h>

@interface MyCustomClass : NSObject {
    UILabel *myLabel;
}

@property (nonatomic, retain) IBOutlet UILabel *myLabel;

- (void)setTheText;

@end

回答1:

Your instance of customClass here is completely unrelated to the NIB. You've instantiated a new object using +alloc. If you want to modify the specific MyCustomClass in your NIB, then FirstViewController needs an IBOutlet that points to it.



回答2:

You don't want to create a new instance of your custom class in your action method.

There are a couple of ways to do what you want.

Option 1 is to give your view controller a reference to your custom object. To do this, create an outlet of type MyCustomClass * in your view controller, connect that outlet to the new object that you created in your XIB file, and then get rid of the allocation in your action method:

- (IBAction)doSomething:(id)sender {       
    [customClass setTheText];
}

Option 2 is to let your CustomClass handle both the label and the action method. To do this, you can simplify things even further. Put an outlet for the UILabel into your CustomClass, and then simply convert your setTheText method into an action:

- (IBAction)setTheText:(id)sender {
    [myLabel setText:@"foo"];
}

Now, connect that action up to your button, and everything should work like a charm.

Note: You should probably use a method name that does not start with "set", since those are commonly used for property setters as part of Cocoa's KVC/KVO system. Instead, I would call it something like changeLabel, or equivalent.



回答3:

UILabel also have a property called text to set the value, you might find that easier.

myObject.myLabel.text = @"Your text";


回答4:

well you called your label two things, first a non-ibaction then an ibaction in the property.