简体   繁体   English

如何使用内部阴影创建圆角UITextField

[英]How to create rounded UITextField with inner shadow

I'm customizing a UITextfield to look like a UISearchbar . 我正在将UITextfield定制为看起来像UISearchbar

I do something like 我做的事情

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

But I see this: 但我明白这一点:

在此输入图像描述

As you can see the inner shadow doesn't follow the border. 正如您所看到的,内部阴影不会跟随边界。

I guess background on a UITextField is an Image, so it no follow to your corner radius. 我猜UITextField上的背景是一个图像,所以它不会跟随你的角半径。
Creating inner shadow is tricky in iOS. 在iOS中创建内部阴影很棘手。 You have 2 options. 你有2个选择。
1) Use image as background for UITextField 1)使用图像作为UITextField背景
2) Set the shadow programmatically (but it look less attractive than option 1). 2)以编程方式设置阴影(但它看起来不像选项1那么有吸引力)。

Here is the code for setting rounded inner shadow for textfield with solution from @Matt Wilding 以下是使用@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];

Don't forget to import 别忘了导入

#import <QuartzCore/QuartzCore.h>

add QuartzCore FrameWork to your project QuartzCore FrameWork添加到您的项目中

And add it in your .m file 并将其添加到.m文件中

#import <QuartzCore/QuartzCore.h>

and use 并使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM