在 Objective-C 中,如何通过 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改变同心圆的颜色.因此,我需要视图控制器中的一种方法来更改 LTHypnosisView 实例的_circleColor属性。我该怎么做?

一个简单的方法,我会LTHypnosisView *mainView视图控制器的属性,setCircleColor公开,然后在change:方法中调用[self.mainView setCircleColor:myColor];

您还可以执行更复杂的操作,例如在LTHypnosisView上定义协议并将视图控制器设置为数据源。 每当调用change:方法时,调用类似[mainView updateColor]的内容,并在updateColor中让它从其数据源读取颜色。

最新更新