UILabel子类不显示文本

时间:2014-01-07 11:45:14

标签: ios objective-c uilabel subclass

我已经将UILabel类子类化为覆盖drawRect:方法。 IB中的标签与创建的子类相关联。它出现在屏幕上,但它不显示任何文本,无论是在IB中设置还是以编程方式设置。标签本身出现在屏幕上,当我记录它的text属性时,它显示OK。

这是我的代码:

MyLabel.h

#import <UIKit/UIKit.h>
@interface MyLabel : UILabel
@end

MyLabel.m

#import "MyLabel.h"
#import <QuartzCore/QuartzCore.h>

@implementation MyLabel


- (void)drawRect:(CGRect)rect {
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = UIGraphicsGetCurrentContext();

    UIColor *borderColor = [UIColor colorWithWhite: .1f alpha: 5.f];
    UIColor *topColor = [UIColor colorWithWhite: .3f alpha: 5.f];
    UIColor *bottomColor = [UIColor colorWithWhite: .5f alpha: 5.f];
    UIColor *innerGlow = [UIColor colorWithWhite: 1.f alpha: .25f];

    NSArray *gradientColors = @[(id)topColor.CGColor, (id)bottomColor.CGColor];
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) gradientColors,  NULL);

    CGFloat bWidth = self.frame.size.width;
    CGFloat bHeight = self.frame.size.height;

    UIBezierPath *roundedRectanglePath = [UIBezierPath bezierPathWithRoundedRect:    CGRectMake(0, 0, bWidth, bHeight)
                                                                cornerRadius: 0];
    [roundedRectanglePath addClip];

    CGGradientRef background = gradient;

    CGContextDrawLinearGradient(context, background, CGPointMake(bWidth / 2.f, 0), CGPointMake(bWidth / 2.f, bHeight), 0);

    [borderColor setStroke];
    roundedRectanglePath.lineWidth = 6;
    [roundedRectanglePath stroke];

    CGFloat glowRadius = 3.f;
    UIBezierPath *innerGlowRect = [UIBezierPath bezierPathWithRoundedRect: CGRectMake(glowRadius, glowRadius, bWidth - 2 * glowRadius, bHeight - 2 * glowRadius)   cornerRadius: 0];
    [innerGlow setStroke];
    innerGlowRect.lineWidth = 3;
    [innerGlowRect stroke];

    CGGradientRelease(gradient);
    CGColorSpaceRelease(colorSpace);
}

@end

也许我需要覆盖drawTextInRect:方法,但我不知道如何。 谢谢你的帮助!

1 个答案:

答案 0 :(得分:9)

您需要致电:

[super drawRect:rect];

在顶部或您的drawRect:方法。如果您需要更多地控制字符串的外观,则需要使用NSString string drawing methods将其绘制成自己。