【问题标题】:Creating subview for superview from another class is not working从另一个类创建超级视图的子视图不起作用
【发布时间】:2012-09-11 05:53:02
【问题描述】:

您好,我是 iOS 新手。

我有 2 个类,一个是父类,另一个是子类。我在父类中有一种方法将创建一个 UIScrollView。我试图通过创建父类的对象从子类调用该父类方法。当我从子类调用时调用该方法,但如果我通过使用 self 在父类中调用相同的方法,它不会创建 UIScrollView,它会创建 UIScrollView。

我不知道我在哪里制造问题。请指导我

//父类中scrollview的创建方法//

  -(void)creatingScroll
{
UIScrollView * propertyScrl = [[UIScrollView alloc]initWithFrame:CGRectMake(10, 200, 320, 160)];
propertyScrl.scrollEnabled = YES;
propertyScrl.showsHorizontalScrollIndicator = YES;
propertyScrl.contentSize = CGSizeMake(600, 60);
propertyScrl.backgroundColor = [UIColor redColor];
[self.view addSubview:propertyScrl];

}

//从子类调用上面的方法//

    ParentViewController *vc = [[ParentViewController alloc]init];

    [vc creatingScroll];

【问题讨论】:

    标签: iphone ios uiviewcontroller uiscrollview parent-child


    【解决方案1】:

    你正在创建另一个 ParentViewController 对象并在该对象上调用 creatingScroll 方法,这不是推送到你的 viewController 上的视图。

    你可以通过协议和委托调用父类方法。

    请参考http://mobiledevelopertips.com/objective-c/the-basics-of-protocols-and-delegates.html

    希望对您有所帮助。快乐编码:)

    【讨论】:

    • 感谢您的回复,我会努力的。
    【解决方案2】:

    既然你已经继承了subclasssuperclass的所有方法,那么你只需在子类中调用[self creatingScroll]即可。

    【讨论】:

    • 感谢您的回复。但是子类已经继承自另一个超类。
    【解决方案3】:
      -(UIScrollView *)creatingScroll
    {
    UIScrollView * propertyScrl = [[UIScrollView alloc]initWithFrame:CGRectMake(10, 200, 320, 160)];
    propertyScrl.scrollEnabled = YES;
    propertyScrl.showsHorizontalScrollIndicator = YES;
    propertyScrl.contentSize = CGSizeMake(600, 60);
    propertyScrl.backgroundColor = [UIColor redColor];
     //[self.view addSubview:propertyScrl];  // don't add here
    
    return propertyScrl;
    
    }
    
    //calling above method from child class or any class//
    probably in viewDidLoad of child class 
    
     ParentViewController * vc = [[ParentViewController alloc]init];
    
      UIScrollView * scrollView = (UIScrollVIew * ) [vc creatingScroll];
    
        [self.view addSubView:scrollView];
    

    【讨论】:

      猜你喜欢
      • 2015-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-03
      相关资源
      最近更新 更多