gpt4 book ai didi

ios - 从 ViewController 类更改自定义 View 类属性

转载 作者:行者123 更新时间:2023-11-28 22:13:11 25 4
gpt4 key购买 nike

我有一个在屏幕上绘制圆圈的自定义 View 。它具有颜色属性。

那个颜色就是圆圈的颜色。

我有另一个 ViewController,它是该 View 的父 View 并拥有另一个 subview - UISegmentControl。

我的愿望是在单击分段按钮时更改颜色属性和 View 颜色。该应用程序运行时没有错误,并且分段操作有效(正如我在 NSLog 中看到的那样)。

那么我在这里缺少什么?(我知道我可能可以将片段添加到另一个 View ,但可以说我不能)

这是我的 View Controller 的加载 View :

-(void)loadView
{
self.segment = [[UISegmentedControl alloc]initWithItems:@[@"red",@"blue",@"green"]];
//this is my costumed view:
BNRHypnosisView *backgroundView = [[BNRHypnosisView alloc]init];
self.view = backgroundView;

CGRect frame = self.segment.frame;
CGRect window = [[UIScreen mainScreen] bounds];
frame.origin.x = (window.size.width-frame.size.width) /2.0;
frame.origin.y = window.size.height -100;

self.segment.frame = frame;
[self.segment addTarget:self action:@selector(action:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:self.segment];

}
-(void)action:(id) sender
{
NSLog(@"%@ was touched",self);
BNRHypnosisView *backgroundView = [[BNRHypnosisView alloc]init];
backgroundView.circleColor = [UIColor redColor];
[backgroundView setNeedsDisplay];

}

最佳答案

不要重新创建新 View ,只需在现有 View 上设置属性即可:

-(void)action:(id) sender
{
NSLog(@"%@ was touched",self);
BNRHypnosisView *backgroundView = (BNRHypnosisView*)self.view;
backgroundView.circleColor = [UIColor redColor];
[backgroundView setNeedsDisplay];
}

作为旁注,我会在 View 的 setCircleColor: 中调用 setNeedsDisplay。这将“更改圆圈颜色需要重绘 View ”的实现细节保留在您的 BNRHypnosisView 类中,这是更好的封装。

关于ios - 从 ViewController 类更改自定义 View 类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22389684/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com