UILabel子类文本消失

时间:2017-01-17 08:14:12

标签: objective-c uilabel subclass

我正在尝试继承UILabel。

代码.h

#import <UIKit/UIKit.h>

IB_DESIGNABLE

@interface PercentLabel : UILabel
@property (nonatomic) IBInspectable CGFloat ratio;
@property (nonatomic) IBInspectable UIColor *color1;
@property (nonatomic) IBInspectable UIColor *color2;


- (void)drawRect:(CGRect)rect;

@end

代码.m

#import "PercentLabel.h"

@implementation PercentLabel

- (void)drawRect:(CGRect)rect {
    // Drawing code
    [super drawRect:rect];

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [_color1 CGColor]);
    CGContextFillRect(context, rect);

}


@end

自定义属性在Storyboard中工作正常,但Rectfill似乎涵盖了我的文本。例如,如果我设置不透明度为0.5的颜色,那么我可以看到颜色背后的文字。

有人可以解释为什么会这样以及如何修复它以便文本显示在顶部?

1 个答案:

答案 0 :(得分:0)

我所做的就是在绘图代码的末尾加上super。

- (void)drawRect:(CGRect)rect {
    // Drawing code

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [_color1 CGColor]);
    CGContextFillRect(context, rect);
     [super drawRect:rect]; //<---

}

Super基本上绘制了UILabel的默认渲染。所以在这种情况下,包括文本的绘制。