如何创建带有内部阴影的圆角UITextField

4

我正在定制一个 UITextfield 使其看起来像一个 UISearchbar

我类似于这样做:

self.back_textfield = [[UITextField alloc]initWithFrame:CGRectMake(5, 7, 310, 30)];
[self.back_textfield setBorderStyle:UITextBorderStyleRoundedRect];
self.back_textfield.layer.cornerRadius = 15.0;

但我看到这个:

enter image description here

正如您所看到的,内部阴影并不遵循边框。
2个回答

6
我猜测UITextField的背景是一张图片,所以它不会遵循您的圆角半径。
在iOS中创建内阴影比较棘手。您有两个选项。
1)使用图像作为UITextField的背景
2)通过编程方式设置阴影(但它看起来不如选项1吸引人)。

以下是设置带有解决方案的文本字段的圆形内阴影的代码,来自@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的宽度应该增加阴影的宽度。 - Gnamm
背景图像将随文本字段调整大小。我认为背景图像将是更好的解决方案。 - Sergey Kuryanov
好的,但如果我改变尺寸很多,背景不会变形吗? - Gnamm
我明白了!只需使用“resizableImageWithCapInsets”。 - Gnamm

4

QuartzCore框架添加到您的项目中

并在您的.m文件中添加它

#import <QuartzCore/QuartzCore.h>

并使用

self.back_textfield.layer.borderWidth = 1.0f; // set as you per your requirement
self.back_textfield.layer.cornerRadius = 5.2f; // set as you per your requirement

1
这是我也使用的好解决方案。奇怪的是苹果没有让它更容易些。 - Leszek Zarna

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接