【问题标题】:UILabel subclass doesn't show textUILabel 子类不显示文本
【发布时间】:2014-01-07 11:45:13
【问题描述】:

我已经继承了 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: 方法,但我不知道怎么做。 感谢您的帮助!

【问题讨论】:

    标签: ios objective-c uilabel subclass


    【解决方案1】:

    您需要致电:

    [super drawRect:rect];
    

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

    【讨论】:

    • 是的,这很好用!谢谢!我知道如果你是 UIView 的子类,你不应该调用 super 方法,但是错过了超类是 UILabel
    • @NikitaShytyk 你为什么不在 UIView 子类上调用 super,而你的类超类可能是 UILabel,但 UILabel 的超类是 UIView。
    • 我正在尝试将 IBDesignable 用于 uilabel 子类,并像这样覆盖 drawRect,但即使我已经放置了 [super drawRect:rect]; 也不会出现文本。怎么了?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    相关资源
    最近更新 更多