如何让这个UILabel可以访问其他类?

时间:2014-04-05 22:33:53

标签: ios objective-c

我有一个类是viewcontroller,它包含:

-(void)testNSTimer
{
    [UIView animateWithDuration:1.0 delay:0 options:UIViewAnimationOptionCurveEaseIn
                     animations:^{ self.view.welcomeBackLabel alpha = 0;} //welcomeBackLabel does not exist.
                     completion:nil];
}

然而,welcomeBackLabel在这种情况下不可用,因为它是在控制器的视图中创建的AKA self.view,如下面的代码所示:

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        welcomeBackLabel = [[UILabel alloc] initWithFrame:CGRectMake(110, -20, 100, 120)]; //welcomeBackLabel is not available for other classes to use, but I want it to be.
        [welcomeBackLabel setText:@"Welcome"];
        [welcomeBackLabel setTextAlignment:NSTextAlignmentCenter];
        UIFont *welcomeFont = [UIFont fontWithName:@"Helvetica-Bold" size:20];
        welcomeBackLabel.font = welcomeFont;
        [welcomeBackLabel setTextColor:[UIColor whiteColor]];
        [welcomeBackLabel setAlpha:0.65];
        [self addSubview:welcomeBackLabel];
    }

我创建了一个属性,但是即使在导入视图的.h文件后,它也未被viewcontroller的类检测到。任何人都可以通过各种方式将welcomeBackLabel用于我的控制器类吗?

编辑:

例如,在我看来,我有:

@property(nonatomic, retain) UILabel *welcomeBackLabel;

我有

#import "view.h"

在我的controller.m中,但它没有将其检测为可用属性o.o

EDIT2:

好的,如果我有HomeScreenView * testView = [[HomeScreenView alloc] init];那么我可以使用属性fine ala testView.welcomebackLabel.etc。当我使用[self setView:testView]为控制器设置视图然后使用self.view.welcomeBackLabel时,它就无法工作......为什么会这样?

2 个答案:

答案 0 :(得分:0)

在班级的.h文件中创建一个@property,它应该可以从其他类中访问。

答案 1 :(得分:0)

在UIViewController中,self.view作为UIView返回。如果你"知道"它是UIView的特定子类,您需要强制转换它以便可以从子类访问方法。你可以内联这个,但为了清楚起见:

MyUIView *v = self.view;
[v myMethod];

或者如果你想要内联:

[(MyUIView *) self.view myMethod];

如果有时是正确的子类,则可以测试:

UIView *v = self.view;
if([v isKindOfClass:[MYUIView class]]) {
    [(MyUIView *) self.view myMethod];
}