UITextField with corner radius only on top or bottom

徘徊边缘 提交于 2019-12-22 09:16:16

问题


I have a UITextField that is added to a view and I'm trying to change it's default appearance.

What I want is to change the corner radius, but only on top / bottom. I'm doing so by doing this:

UIBezierPath *usernameMaskPathWithRadiusTop = [UIBezierPath bezierPathWithRoundedRect:username.bounds
                                                                    byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight)
                                                                          cornerRadii:CGSizeMake(4.0, 4.0)];

UIBezierPath *passwordMaskPathWithRadiusBottom = [UIBezierPath bezierPathWithRoundedRect:password.bounds
                                                                       byRoundingCorners:(UIRectCornerBottomLeft | UIRectCornerBottomRight)
                                                                             cornerRadii:CGSizeMake(4.0, 4.0)];

CAShapeLayer *usernameMaskLayer = [[CAShapeLayer alloc] init];
usernameMaskLayer.frame = username.bounds;
usernameMaskLayer.path = usernameMaskPathWithRadiusTop.CGPath;

CAShapeLayer *passwordMaskLayer = [[CAShapeLayer alloc] init];
passwordMaskLayer.frame = password.bounds;
passwordMaskLayer.path = passwordMaskPathWithRadiusBottom.CGPath;


[username setTextAlignment:NSTextAlignmentLeft];
[username setClearButtonMode:UITextFieldViewModeWhileEditing];
usernameLayer.shadowOpacity = 0.0;
[usernameLayer setMask:usernameMaskLayer];

[password setTextAlignment:NSTextAlignmentLeft];
[username setClearButtonMode:UITextFieldViewModeWhileEditing];
passwordLayer.shadowOpacity = 0.0;
[passwordLayer setMask:passwordMaskLayer];

Where UITextField *username, UITextField *password and the CAShapeLayer *usernameLayer = username.layer and CAShapeLayer *passwordLayer = password.layer are defined as described.

The issue is that after I perform that above, I get no fields at all, actually they are there but everything is transparent, text and background color. I'm not sure how to get that back or how to fix whatever I'm doing wrong.

How exactly can I do what I'm trying right ?


回答1:


It seems like what I had to do is instead of setting a mask I had to add as sublayer:

[username.layer addSublayer:usernameMaskLayer];

// instead of the old

[usernameLayer setMask:usernameMaskLayer];

And then for setting a background I just had to setFillColor on the usernameMaskLayer.



来源:https://stackoverflow.com/questions/19910361/uitextfield-with-corner-radius-only-on-top-or-bottom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!