试图给UILabel一个阴影,但它不会出现

时间:2013-05-19 21:15:40

标签: ios objective-c ios6 uiview uilabel

我正试图在我的应用程序的一个类中给一个标签一个阴影,但它根本不起作用。什么都没有出现。我做错了什么?

// Set label properties
titleLabel.font = [UIFont boldSystemFontOfSize:TITLE_FONT_SIZE];
titleLabel.adjustsFontSizeToFitWidth = NO;
titleLabel.opaque = YES;
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.textColor = titleLabelColor;
titleLabel.shadowColor = [UIColor blackColor];
titleLabel.shadowOffset = CGSizeMake(10, 10);

它只是白色,没有阴影。

3 个答案:

答案 0 :(得分:13)

在将titleLabel添加到self.view

之前,只需添加此行
 titleLabel.layer.masksToBounds = NO;

祝你好运!!

答案 1 :(得分:3)

我希望您了解类别?

创建类别将是更好的选择:

Command + N > Objective-C Category > Category = Animation & Category on = UIView 这将创建名为UIView+Animation.hUIView+Animation.m

的2个文件

UIView+Animation.h档案

#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>

@interface UIView (Animation)
- (void)setBackgroundShadow:(UIColor *)shadowColor CGSize:(CGSize)CGSize shadowOpacity:(float)shadowOpacity shadowRadius:(float)shadowRadius;
@end

UIView+Animation.m档案

#import "UIView+Animation.h"

@implementation UIView (Animation)
- (void)setBackgroundShadow:(UIColor *)shadowColor CGSize:(CGSize)CGSize shadowOpacity:(float)shadowOpacity shadowRadius:(float)shadowRadius
{
    self.layer.shadowColor = shadowColor.CGColor;
    self.layer.shadowOffset = CGSize;
    self.layer.shadowOpacity = shadowOpacity;
    self.layer.shadowRadius = shadowRadius;
    self.clipsToBounds = NO;
}

UIView+Animation.h的任何内容中导入viewController并将其称为:

[self.titleLabel  setBackgroundShadow:[UIColor grayColor] CGSize:CGSizeMake(0, 5) shadowOpacity:1 shadowRadius:5.0];

答案 2 :(得分:0)

只需确保分配UILabel并为标签设置框架。并确保将视图添加到子视图中。像这样:

    titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 30)];
    titleLabel.font = [UIFont boldSystemFontOfSize:14];
    titleLabel.adjustsFontSizeToFitWidth = NO;
    titleLabel.opaque = YES;
    titleLabel.text = @"My Label";
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.shadowColor = [UIColor blackColor];
    titleLabel.shadowOffset = CGSizeMake(5, 5);
    [myView addSubview:titleLabel];
    [titleLabel release];
阴影偏移的

值10非常大。您可以根据您的要求调整值。