繁体   English   中英

iOS子视图最佳做法

[英]iOS subview best practice

所以这就是我所拥有的; 一个具有根UIView (子类)的ViewController ,该UIView具有一个子视图,即UISegmentedControl UIView绘制同心圆, UISegmentedControl更改这些圆的颜色。 为了做到这一点,我在ViewControllers loadView中创建了UIView并将其添加到self.view中,然后制作了UISegmentedControl并将其添加为UIView的子视图。 然后,我将UIView设置为UISegmentControl的目标,并在UIView实现了一种方法来更改颜色并将其设置为操作。 这一切都起作用。

一些代码供参考

//setting up view hierarchy in viewcontroller.m

- (void)loadView{
    BNRHypnosisView *backgroundView = [[BNRHypnosisView alloc]init];
    self.view = backgroundView;
    UISegmentedControl *segmentedControl = [[UISegmentedControl alloc]initWithItems:@[@"Red",@"Green",@"Blue"]];
    [segmentedControl addTarget:backgroundView
                         action:@selector(changeColor:)
               forControlEvents:UIControlEventValueChanged];
    [backgroundView addSubview:segmentedControl];
  }


//action
 - (void)changeColor:(UISegmentedControl *)sender{

      switch (sender.selectedSegmentIndex) {
        case 0:
          self.circleColor = [UIColor redColor];
          break;

        case 1:
          self.circleColor = [UIColor greenColor];
          break;

        case 2:
          self.circleColor = [UIColor blackColor];
          break;
      }
    }

所以对于我的问题...在这里,我将超级视图视为子视图的控制器,这是错误的吗? 应该让一切都由拥有我的UIView的视图控制器处理。 如果是这样,在这种情况下我该怎么办?

-谢谢

并确保任何人都能接受,这是BNR iOS编程书的挑战之一:]

在MVC中,这是错误的。 如您所说,您对控制器进行了查看,但绝对不应该这样。 您的目标应该是使大多数类独立于其他类(松耦合)。

在您的情况下,应将所有代码(尤其是目标操作代码)移至视图控制器。 将操作更改为以viewDidLoad中的viewController为目标:

[segmentedControl addTarget:self
                     action:@selector(changeColor:)
           forControlEvents:UIControlEventValueChanged];
[backgroundView addSubview:segmentedControl];

并将changeColor方法移动到视图控制器,并将该方法的发送方转换为UISegmented控件:

- (void)changeColor:(id)sender{

     UISegmentedControl *segControl = (UISegmentedControl *) sender;

      switch (segControl.selectedSegmentIndex) {
        case 0:
          circleView.circleColor = [UIColor redColor];
          break;

        case 1:
          circleView.circleColor = [UIColor greenColor];
          break;

        case 2:
          circleView.circleColor = [UIColor blackColor];
          break;
      }
    }

为此,您需要为circleView提供一个属性,因此在视图控制器中创建一个属性,并在创建circleView时将其分配给该属性。

@proprety (nonatomic, strong) BNRHypnosisView *circleView;

并在您的loadView:方法中:

- (void)loadView{
    self.circleView = [[BNRHypnosisView alloc]init];
    self.view = self.circleView;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM