如何创建带有内阴影的圆形 UITextField [英] How to create rounded UITextField with inner shadow
问题描述
我正在自定义一个 UITextfield
以使其看起来像一个 UISearchbar
.
I'm customizing a UITextfield
to look like a UISearchbar
.
我做类似的事情
self.back_textfield = [[UITextField alloc]initWithFrame:CGRectMake(5, 7, 310, 30)];
[self.back_textfield setBorderStyle:UITextBorderStyleRoundedRect];
self.back_textfield.layer.cornerRadius = 15.0;
但我看到了:
如您所见,内部阴影不跟随边框.
As you can see the inner shadow doesn't follow the border.
推荐答案
我猜 UITextField
上的背景是一个图像,所以它不会跟随你的圆角半径.
在 iOS 中创建内部阴影很棘手.您有 2 个选择.
1) 使用图像作为 UITextField
的背景2) 以编程方式设置阴影(但它看起来不如选项 1 有吸引力).
I guess background on a UITextField
is an Image, so it no follow to your corner radius.
Creating inner shadow is tricky in iOS. You have 2 options.
1) Use image as background for UITextField
2) Set the shadow programmatically (but it look less attractive than option 1).
这是使用@Matt Wilding 的解决方案为文本字段设置圆形内阴影的代码
Here is the code for setting rounded inner shadow for textfield with solution from @Matt Wilding
_textField.layer.cornerRadius = 10.0f;
CAShapeLayer* shadowLayer = [CAShapeLayer layer];
[shadowLayer setFrame:_textField.bounds];
// Standard shadow stuff
[shadowLayer setShadowColor:[[UIColor colorWithWhite:0 alpha:1] CGColor]];
[shadowLayer setShadowOffset:CGSizeMake(0.0f, 0.0f)];
[shadowLayer setShadowOpacity:1.0f];
[shadowLayer setShadowRadius:4];
// Causes the inner region in this example to NOT be filled.
[shadowLayer setFillRule:kCAFillRuleEvenOdd];
// Create the larger rectangle path.
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectInset(_textField.bounds, -42, -42));
// Add the inner path so it's subtracted from the outer path.
// someInnerPath could be a simple bounds rect, or maybe
// a rounded one for some extra fanciness.
CGPathRef someInnerPath = [UIBezierPath bezierPathWithRoundedRect:_textField.bounds cornerRadius:10.0f].CGPath;
CGPathAddPath(path, NULL, someInnerPath);
CGPathCloseSubpath(path);
[shadowLayer setPath:path];
CGPathRelease(path);
[[_textField layer] addSublayer:shadowLayer];
CAShapeLayer* maskLayer = [CAShapeLayer layer];
[maskLayer setPath:someInnerPath];
[shadowLayer setMask:maskLayer];
别忘了导入
#import <QuartzCore/QuartzCore.h>
这篇关于如何创建带有内阴影的圆形 UITextField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!