我有一些代码试图通过图像在 UIView 中设置背景颜色,但我只看到黑屏。这是我所做的-
- 有一个
UIViewController
类和一个UIView
类 UIView
类有一个drawRect
函数。- 在
UIViewController
viewDidLoad
函数中创建UIView
类 - 之后
UIView
中的drawRect
被调用。
这是UIView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect
{
UIColor *backGround = [UIColor colorWithPatternImage:[UIImage imageNamed:@"test.png"]];
self.backgroundColor = backGround;
}
在调试器中验证 backGround
对象在执行后不为 nil。还测试了 test.png 文件是否存在,我可以用它创建一个 UIImageView
。
如果我在 initWithFrame
函数中设置 backgroundColor
而不是 drawRect()
,我发现结果是一样的
我想设置 backgroundColor
的原因是我正在绘制棋盘游戏并且我想使用图像作为背景。这样我就可以在图像上画线(板)。
最佳答案
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
// Initialization code
UIColor *backGround = [UIColor colorWithPatternImage:[UIImage imageNamed:@"test.png"]];
self.backgroundColor = backGround;
}
return self;
}
更改 drawRect 中的背景将不起作用。必须在 init 方法中对其进行任何更改。
关于ios - 设置 backgroundColor 似乎不适用于 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22550049/