4

我正在定制 aUITextfield看起来像 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;

但我看到了这个:

在此处输入图像描述

如您所见,内部阴影不跟随边界。

4

2 回答 2

6

我猜 a 上的背景UITextField是一个图像,所以它不会跟随你的拐角半径。
在 iOS 中创建内部阴影很棘手。您有 2 个选项。
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>
于 2013-09-07T08:39:20.903 回答
4

QuartzCoreFrameWork 添加到您的项目中

并将其添加到您的.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
于 2013-09-07T08:25:12.033 回答