Set background color for only part of UIView

前端 未结 6 2577
生来不讨喜
生来不讨喜 2021-02-20 09:33

I want the bottom (not quite half) of my UIView to be a different color than the top.

I\'m wondering if I should create a CGRect and then color that? Is this along the r

6条回答
  •  没有蜡笔的小新
    2021-02-20 10:03

    Override the drawRect method of your UIView Subclass. The following code will make the top half of your view black and the bottom half of your view red.

    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    - (void)drawRect:(CGRect)rect
    {
        // Top View
        CGRect topRect = {CGRectGetMinX(self.bounds), CGRectGetMinY(self.bounds), CGRectGetMaxX(self.bounds), CGRectGetMaxY(self.bounds)};
        [[UIColor blackColor] setFill];
        UIRectFill(topRect);
    
        // Bottom View
        CGRect bottomRect = {CGRectGetMinX(self.bounds), CGRectGetMidY(self.bounds), CGRectGetMaxX(self.bounds), CGRectGetMidY(self.bounds)};
        [[UIColor redColor] setFill];
        UIRectFill(bottomRect);
    }
    

    NOTE: Also you can only override the drawRect: method when you subclass a UIView. Based on your comment view I have a feeling this is not what you are doing.

提交回复
热议问题