How to create a rounded UITextField with an inner shadow

I configure UITextfield as a UISearchbar .

I'm doing 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:

enter image description here

As you can see, the inner shadow does not follow the border.

+4
source share
2 answers

I think the background on the UITextField is an image, so it doesn't match your angle. Creating the inner shadow is difficult in iOS. You have 2 options.
1) Use image as background for UITextField
2) Set the shadow programmatically (but it looks less attractive than option 1).

Here is the code to set the rounded inner shadow for the text box with the 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 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]; 

Do not forget to import

 #import <QuartzCore/QuartzCore.h> 
+6
source

add QuartzCore FrameWork to your project

And add it to your .m file

 #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 
+4
source

Source: https://habr.com/ru/post/1501059/


All Articles