gpt4 book ai didi

iphone - 帮助理解 UIVIewController 和 UIView 子类之间的交互

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

目前的情况是这样的:

TestViewController.h:

#import <UIKit/UIKit.h>
@interface TestViewController : UIViewController {
}
@end

TestViewController.m:

#import "TestViewController.h"
#import "draw.h"
@implementation TestViewController

- (void)viewDidLoad {
draw.rectColor = [UIColor colorWithHue:0.6 saturation:0.6 brightness:0.6 alpha:1].CGColor;
[draw setNeedsDisplay];
[super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}

- (void)dealloc {
[super dealloc];
}
@end

绘制.h:

#import <UIKit/UIKit.h>

@interface draw : UIView {
UIColor* rectColor;
}

@property (retain) UIColor* rectColor;

@end

绘制.m:

#import "draw.h"

@implementation draw

@synthesize rectColor;

- (id)initWithFrame:(CGRect)frame {

self = [super initWithFrame:frame];
if (self) {
// Initialization code.
}
return self;
}

- (void)drawRect:(CGRect)rectangle {

CGContextRef context = UIGraphicsGetCurrentContext();
CGColorRef myColor = [UIColor colorWithHue:0 saturation:1 brightness:0.61 alpha:1].CGColor;
CGContextSetFillColorWithColor(context, myColor);
CGContextAddRect(context, CGRectMake(0, 0, 95.0, 110.0));
CGContextFillPath(context);
}

- (void)dealloc {
[super dealloc];
}

@end

然后在 Interface Builder 中我创建了一个 90x115 UIView 并将其类标识设置为“draw”。当我运行应用程序(没有两条非编译行)时,它会在屏幕中间显示一个漂亮的红色矩形。我的目标是能够从 TestViewController 中更改矩形的颜色。但是,当我编译测试应用程序时,出现以下编译器错误:

error: accessing unknown 'setRectColor:' class method
error: object cannot be set - either readonly property or no setter found
warning: 'draw' may not respond to '+setNeedsDisplay'

我知道我缺少 TestViewController 和绘图之间的“链接”,但不知道如何实现它。我尝试了各种技巧,但没有任何效果。有人可以解释一下需要做什么才能做到

draw.rectColor = [UIColor colorWithHue:0.6 saturation:0.6 brightness:0.6 alpha:1].CGColor;
[draw setNeedsDisplay];

编译并运行?(我将利用这些知识在 TestViewController 中创建不同的方法,我只是在 viewDidLoad 中测试它)

最佳答案

在您发布的代码中,您设置了 rectColor 属性并在绘制时调用 setNeedsDisplay: ,但绘制是您的类。您需要对实例执行此操作。您不需要为此创建新属性,因为 UIViewController 定义了 View 属性。只需在 viewDidLoad 方法中使用 self.view 而不是 draw 即可。另外,删除该行末尾的 .CGColor

其次,您的drawRect:方法会忽略该颜色并使用它自己的颜色。改变

CGColorRef myColor = [UIColor colorWithHue:0 saturation:1 brightness:0.61 alpha:1].CGColor;

CGColorRef myColor = self.rectColor.CGColor;

关于iphone - 帮助理解 UIVIewController 和 UIView 子类之间的交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4393935/

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