UILabel、UITextField可以直接设置shadow属性:
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(30, 30, 300, 50)];
label.text = @"UILabel文字阴影效果";
//阴影颜色
label.shadowColor = [UIColor redColor];
//阴影偏移 x,y为正表示向右下偏移
label.shadowOffset = CGSizeMake(1, 1);
[self.view addSubview:label];
阴影可以设置的属性比较少,如果要进行更多的设置,就要在layer层进行设置,但要把背景色设置为透明。比如UITextView,就必须在layer进行设置,因为UITextView没有提供shadow相关的属性(吐槽一下连placeholder属性都没有。。。)
UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(30, 80, 300, 50)];
textView.backgroundColor = [UIColor clearColor];
textView.font = [UIFont systemFontOfSize:17];
[self.view addSubview:textView];
textView.text = @"UITextView文字阴影效果";
//阴影透明度
textView.layer.shadowOpacity = 1.0;
//阴影宽度
textView.layer.shadowRadius = 1.0;
//阴影颜色
textView.layer.shadowColor = [UIColor redColor].CGColor;
//映影偏移
textView.layer.shadowOffset = CGSizeMake(1, 1);
还有一种方案就是利用NSAttributedString属性字符串来设置阴影了,这种方法还可以控制range:
NSShadow *shadow = [[NSShadow alloc]init];
shadow.shadowBlurRadius = 1.0;
shadow.shadowOffset = CGSizeMake(1, 1);
shadow.shadowColor = [UIColor redColor];
[_attributedString addAttribute:NSShadowAttributeName
value:shadow
range:NSMakeRange(1, _attributedString.length-1)];