繁体   English   中英

在Objective-C中,如何通过UIControl更改类内部实例的属性?

[英]In Objective-C, how can I change the property of an instance inside of class via UIControl?

这个问题是关于iOS编程第4版的练习6.9。 我有一堂课,可以画同心圆并通过随机更改其颜色来响应触摸。

这是视图的实现:

@implementation LTHypnosisView
- (instancetype) initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self){
        self.backgroundColor = [UIColor clearColor];
        self.circleColor = [UIColor lightGrayColor];
    }
    return self;
}    

- (void)drawRect:(CGRect)rect {
    //Draw the circles
}

- (void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    float red = (arc4random() % 100) /100.0;
    float green = (arc4random() % 100) /100.0;
    float blue = (arc4random() % 100) /100.0;
    UIColor *randomColor = [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
    self.circleColor = randomColor;
}

- (void) setCircleColor:(UIColor *)circleColor{
    _circleColor = circleColor;
    [self setNeedsDisplay];
}
@end

这是viewController的实现:

@implementation LTHypnosisViewController
- (void) viewDidLoad{
    CGRect screenRect = self.view.bounds;
    LTHypnosisView *mainView = [[LTHypnosisView alloc] initWithFrame:screenRect];
    [self addSubview:mainView]
    NSArray *items = @[@"Red",@"Green",@"Blue"];
    UISegmentedControl *segControl = [[UISegmentedControl alloc] initWithItems:items];
    [segControl addTarget:self
                   action:@selector(change:)
         forControlEvents:UIControlEventValueChanged];
    segControl.frame = CGRectMake(10, 50, self.view.bounds.size.width-20, 60);
    segControl.selectedSegmentIndex = 0;
    segControl.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:segControl];
}

- (void) change:(UISegmentedControl*)sender{
    switch (sender.selectedSegmentIndex) {
        //How should I write here??
    }
}

@end

我想使用UISegmentedControl更改同心圆的颜色。 因此,我需要在viewController中使用一种方法来更改LTHypnosisView实例的_circleColor属性。 我怎样才能做到这一点?

一种简单的方法是,将LTHypnosisView *mainView设置为视图控制器的属性,将setCircleColor公开,然后进行change:方法调用[self.mainView setCircleColor:myColor];

您还可以做一些更复杂的事情,例如在LTHypnosisView上定义协议并将视图控制器设置为数据源。 每当调用change:方法时,都调用[mainView updateColor]之类的方法,并在updateColor中使其从其数据源读取颜色。

暂无
暂无

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

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