简体   繁体   中英

UITextField with corner radius only on top or bottom

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 ?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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