簡體   English   中英

設置 UIView 背景顏色的 self

[英]setting self of UIView background color

我正在嘗試從自定義視圖 class 的.m 內部執行此操作,該視圖不是從 XIB 加載的,而是以編程方式:

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
    // Initialization code

    self.backgroundColor=[UIColor redcolor];
}
return self;
}

無論我將背景顏色放在 initWithFrame 還是其他方法中,我都有相同的結果。 背景顏色屬性不占用。 從擁有此自定義視圖的 controller 中,我可以很好地設置背景顏色,其中:

self.mycustomview.backgroundColor=[UIColor redcolor];

但我想從自定義視圖本身中做到這一點,保持這樣的獨立。 controller 和自定義視圖導入 UIKit。

我也試過這個,可以從 Code Sense 獲得:

    self.View.backgroundColor=[UIColor redcolor];

但這也不起作用。 我在這里嘗試了viewView 我確定我忽略了一些非常明顯的東西。

在視圖 controller 我有這個,它工作正常。 自定義視圖稱為“mapButtons.h”:

- (void)viewDidLoad
{
CGRect frame=CGRectMake(0, 0, 320, 460);
self.mapButtons=[[mapButtons alloc] initWithFrame:frame];
self.mapButtons.backgroundColor=[UIColor redColor];

[self.view addSubview:self.mapButtons];

自定義視圖的.h 是這樣的:

#import <UIKit/UIKit.h>

@interface mapButtons : UIView

如果您的視圖是從 XIB 創建的(即,您使用 Interface Builder 將其添加到其他視圖), -initWithFrame:不會被調用。 從 XIB 加載的 object 接收-initWithCoder:代替。 嘗試這個:

- (id)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];

    if(self)
    {
        self.backgroundColor = [UIColor redColor];
    }

    return self;
}

我已經再次測試,這是我正在做的工作的完整來源

// MapButtons.h
#import <UIKit/UIKit.h>

// As a note you normally define class names starting with a capital letter
// but I did test this with mapButtons as you had it
@interface MapButtons : UIView

@end

// MapButtons.m
#import "mapButtons.h"

@implementation mapButtons

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
      // Initialization code
      self.backgroundColor = [UIColor redColor];
    }
    return self;
}

@end

// TestAppDelegate.m
@implementation TestAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{  
    MapButtons *view = [[MapButtons alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    [self.window addSubview:view];

    [self.window makeKeyAndVisible];
    return YES;
}

xcode 不是自動完成的事實很奇怪,但我似乎間歇性地遇到這個問題,所以我沒有真正的解決方案。 人們有時建議刪除項目派生數據並重新啟動 xcode。

暫無
暫無

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

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