【问题标题】:How can UIView access property of UIViewController?UIView 如何访问 UIViewController 的属性?
【发布时间】:2010-12-22 19:27:12
【问题描述】:

有一个UIViewController,它有一个实例变量NSInteger。我在UIViewController.h 文件中将其声明为:

NSInterger *theNum;
...
@property NSInteger *theNum;

然后,我在它的.m 文件中合成它:

@synthesize theNum;

这个UIViewController的视图(UIView)有一个方法doSomething需要访问theNum的值。

这是这个“视图”的.m 文件中的代码:

-(void)doSomething {

NSInteger *myNum = self.superview.theNum; //error: request for member 'theNum' in something not a structure or union

// do something

}

那么,我怎样才能将theNum 的值从UIViewController 转换为UIView?

【问题讨论】:

    标签: iphone ios uiview uiviewcontroller ios4


    【解决方案1】:

    您需要将UIViewController 中的号码传递给UIView。控制器应该知道视图,而不是相反。

    //SomeView.h
    @interface SomeView : UIView
    NSInteger theNum; 
    //You have NSInteger *theNum. I am guessing you made that a pointer by accident
    }
    
    @property(assign) NSInteger theNum;
    
    @end
    
    //SomeViewController.m
    
    -(void)viewDidLoad
    {
       [super viewDidLoad];
       ((SomeView*)self.view).theNum = theNum;//This theNum belongs to the ViewController
    }
    

    【讨论】:

      【解决方案2】:

      我会说通常doSomething 将是视图控制器,而视图只是drawStuff。

      但无论如何,superview 不是视图控制器,它是您将此视图添加为子视图的视图。
      视图通常没有任何指向视图控制器的指针,因为通常假定它基本上只是绘制自身及其子视图。

      如果您真的希望视图本身为doSomething,您可以在视图类中添加viewController 属性并在视图控制器创建视图时设置它。

      【讨论】:

      • 向视图添加视图控制器是不明智的。
      • @joshpaul 我同意,这就是我写前四段的原因。
      猜你喜欢
      • 2012-08-02
      • 1970-01-01
      • 1970-01-01
      • 2012-07-01
      • 1970-01-01
      • 2011-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多