【问题标题】:Make UiView sub class but background color show black color使 UiView 子类但背景颜色显示黑色
【发布时间】:2013-12-12 20:36:35
【问题描述】:

我采用了一个 UiView 子类,但它的背景颜色没有改变

这个类我用的是这些方法

- (id)initWithFrame:(CGRect)frame
{
   self = [super initWithFrame:CGRectMake(50, 80, 200, 200)];
   if (self)
       {
       // Initialization code
       }
   return self;
}

- (void)drawRect:(CGRect)rect{

   CGContextRef context = UIGraphicsGetCurrentContext();
   [[UIColor darkGrayColor]setFill];     
   CGContextClearRect(context, rect);
   CGContextSetLineWidth(context, 2.0);

   CGContextBeginPath(context);
   CGContextSetStrokeColorWithColor(context, [UIColor orangeColor].CGColor);
   CGContextMoveToPoint(context, 1, 1);
   CGContextAddLineToPoint(context, 100, 100);
   CGContextStrokePath(context); // and draw 
}

我将这个类调用到主视图控制器

Newclass *obj =[[Newsclass alloc]init]; 
obj.backgroundColor =[UIColor redColor];
[self.view addsubview :obj];

但默认情况下背景颜色显示黑色。它没有改变

如果我使用框架方法实现背景颜色代码初始化或

绘制rect方法比不改变。

如果我编码它

- (id)initWithCoder:(NSCoder*)aDecoder 

比它的方法没有被调用 请建议我 UIview 子类黑色背景颜色如何更改

【问题讨论】:

    标签: iphone


    【解决方案1】:

    首先,你应该在 UIView 文件中做颜色部分。

    if (self = [super initWithFrame:CGRectMake(220,60, 100, 300)])
    {
        self.backgroundColor =[UIColor greenColor];
    }
    

    在这种情况下你怎么不需要做... ;)

    它肯定会改变你的背景颜色。但接下来发生的是调用 Draw rect 方法,您的颜色不再可见,因为 draw rect 方法在其上方绘制了一个视图(无论您在该方法中绘制什么)。

    - (void)drawRect:(CGRect)rect
    {
    
       CGContextRef context = UIGraphicsGetCurrentContext();
       CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
    
       CGRect rectangle = CGRectMake(0,0,200,300);
    
       CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
    
       CGContextFillRect(context, rectangle);
    }
    

    您不能直接设置 cgcontext 的背景颜色,您必须用颜色填充该上下文。 请确保将矩形替换为视图的矩形框。它对我来说就像一个魅力。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-30
      • 2014-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多