2014-01-07 40 views
1

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

这里是我的代码:

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:方法,但我不知道怎么办。 感谢您的帮助!

回答

8

你需要调用:

[super drawRect:rect]; 

在顶部或您的drawRect:方法。如果你需要更多的控制字符串的方式,你需要用NSString string drawing methods来描绘​​你自己。

+0

是的,这个工程太棒了!谢谢!我知道你不应该调用超类方法,如果你继承UIView,但错过了超类UILabel –

+0

@NikitaShytyk为什么你不会在UIView子类上调用超类,而你的类超类可能是UILabel,但是UILabel的超类是UIView。 –

+0

我正在尝试使用IBDesignable作为uilabel子类,并且像这样重写drawRect,但即使已经放置了[super drawRect:rect];也没有文本出现。哪里不对? – GeneCode