Drop Shadow on UITextField text

前端 未结 4 531
再見小時候
再見小時候 2020-11-30 17:56

Is it possible to add a shadow to the text in a UITextField?

4条回答
  •  庸人自扰
    2020-11-30 18:40

    Although the method of applying the shadow directly to the UITextView will work, it's the wrong way to do this. By adding the shadow directly with a clear background color, all subviews will get the shadow, even the cursor.

    The approach that should be used is with 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;
    

    However textView.attributedText is for iOS6. If you must support lower versions, you could use the following approach. (Dont forget to add #import )

    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;
    

提交回复
热议问题