簡體   English   中英

設置backgroundColor似乎不適用於UIView

[英]Setting backgroundColor doesn't seem to work on a UIView

我有一些代碼嘗試從圖像中設置UIView中的backgroundColor,但我看到的只是黑屏。 這是我做的 -

  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方法中完成。

只需在viewDidLoad嘗試一下

-(void)viewDidLoad{
    UIColor *backGround = [UIColor colorWithPatternImage:[UIImage imageNamed:@"test.png"]];
        self.view.backgroundColor = backGround;

//.....
}

編輯:

對於你的問題:

繪圖由與視圖關聯的圖層完成。 看起來,在您的環境中,背景色圖層在調用-drawRect:方法之前正在進行繪制。 重繪圖層時,也會調用-drawRect:方法。 因此,在更改背景顏色后,在背景圖層再次繪制之前,您看不到任何更改,您可以告訴它,因為您的-drawRect:再次被調用。 這里 && 查看更多信息

在drawRect方法中,您不應該設置背景。 你必須做繪畫,你想在視圖中繪制。 背景視圖是單獨的視圖。 如果要在自定義視圖中設置背景視圖,請在init方法中執行,否則可以在視圖控制器中(任何位置)執行此操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM