【问题标题】:How to add text shadows to a UITextView?如何将文本阴影添加到 UITextView?
【发布时间】:2012-05-25 05:29:56
【问题描述】:

我一直在寻找一种简单的方法来为 UITextView 的 text 添加阴影,就像在 UILabel 中一样。我发现this question 有一个答案应该是这样做的,但是,为什么会这样是没有意义的。

问题:给 UITextView 本身的图层添加阴影不应该影响里面的文字,而是应该阴影整个对象,对吧?

在我的情况下,即使将阴影添加到 textview 的图层也没有任何效果(即使在添加 QuartzCore 标头之后)。

【问题讨论】:

    标签: objective-c ios uitextview quartz-graphics


    【解决方案1】:

    我试过了,发现你应该将 UITextView 的背景色设置为透明, 所以阴影应该可以工作

        UITextView *text = [[[UITextView alloc] initWithFrame:CGRectMake(0, 0, 150, 100)] autorelease];
        text.layer.shadowColor = [[UIColor whiteColor] CGColor];
        text.layer.shadowOffset = CGSizeMake(2.0f, 2.0f);
        text.layer.shadowOpacity = 1.0f;
        text.layer.shadowRadius = 1.0f;
        text.textColor  = [UIColor blackColor];
    
                //here is important!!!!
        text.backgroundColor = [UIColor clearColor];
    
        text.text = @"test\nok!";
        text.font = [UIFont systemFontOfSize:50];
    
        [self.view addSubview:text];
    

    【讨论】:

      【解决方案2】:

      @adali 的回答会起作用,但它是错误的。您不应将阴影添加到 UITextView 本身以影响内部的可见视图。如您所见,通过将阴影应用于UITextView,光标也将具有阴影。

      应该使用的方法是NSAttributedString

      NSMutableAttributedString* attString = [[NSMutableAttributedString alloc] initWithString:textView.text];
      NSRange range = NSMakeRange(0, [attString length]);
      
      [attString addAttribute:NSFontAttributeName value:textView.font range:range];
      [attString addAttribute:NSForegroundColorAttributeName value:textView.textColor range:range];
      
      NSShadow* shadow = [[NSShadow alloc] init];
      shadow.shadowColor = [UIColor whiteColor];
      shadow.shadowOffset = CGSizeMake(0.0f, 1.0f);
      [attString addAttribute:NSShadowAttributeName value:shadow range:range];
      
      textView.attributedText = attString;
      

      但是textView.attributedText 是针对 iOS6 的。如果一定要支持低版本,可以使用下面的方法。

      CALayer *textLayer = (CALayer *)[textView.layer.sublayers objectAtIndex:0];
      textLayer.shadowColor = [UIColor whiteColor].CGColor;
      textLayer.shadowOffset = CGSizeMake(0.0f, 1.0f);
      textLayer.shadowOpacity = 1.0f;
      textLayer.shadowRadius = 0.0f;
      

      【讨论】:

      • 哈哈,我回答这个问题的时候没有发布iOS6 :)
      • 是的,很难让这些 cmets 保持最新:P
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多