ios - 设置 backgroundColor 似乎不适用于 UIView

标签 ios objective-c uiview

我有一些代码试图通过图像在 UIView 中设置背景颜色,但我只看到黑屏。这是我所做的-

  1. 有一个UIViewController类和一个UIView
  2. UIView 类有一个drawRect 函数。
  3. UIViewController viewDidLoad 函数中创建 UIView
  4. 之后 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/

相关文章:

javascript - 如何拦截IOS上UIWebview中的Button点击?

ios - 使用 Alamofire 获取 JSON 并解码 - Swift 4

iphone - UISegmentedControl 不检测 iOS5 中的段更改

ios - 带有 Storyboard的部分 View

ios - NSCounted 设置忽略属性

ios - 如何将新的类文件添加到 Xcode 中的组?

objective-c - 在 touchesMoved 上获取 UIView 的旋转方向

c++ - 函数调用-Objective C

ios - 使用 swift 和 UIViewAnimation 逐渐填充形状?

iphone - 为什么我的 UIView subview 没有在父 View 中呈现? (附代码)