带圆angular的UITextField只在顶部

我想实现一个只有左上angular和右上angular有圆angular的UITextField。

我知道setter方法setCornerRadius:这是UITextField的默认选项,但是这个选项只允许我把txtfield的所有四个angular都舍去,但是我只希望顶部的angular是圆的。

我现在在几个小时左右就搞乱了,我已经通过Appple的文档读了十几遍,但是我仍然无法知道为什么我的代码不能工作:

- (id) init { // init elements UITextField *txt_password = [[UITextField alloc] init]; UIView *txt_password_paddingVc = [[UIView alloc] initWithFrame:CGRectMake(0,0,10,35)]; // configure txtfield [txt_password setSecureTextEntry:YES]; [txt_password setDelegate:self]; [txt_password setTag:100]; [txt_password setPlaceholder:t(@"App Password")]; [txt_password setLeftView:txt_password_paddingVc]; [txt_password setRightView:txt_password_paddingVc]; [txt_password setBackgroundColor:[UIColor whiteColor]]; [txt_password setLeftViewMode:UITextFieldViewModeAlways]; [txt_password setRightViewMode:UITextFieldViewModeAlways]; [txt_password setTranslatesAutoresizingMaskIntoConstraints:NO]; [txt_password setAutocapitalizationType:UITextAutocapitalizationTypeNone]; [txt_password setAutocorrectionType:UITextAutocorrectionTypeNo]; [txt_password.layer setBorderColor:[UIColor colorWithRed:228/255.0 green:228/255.0 blue:228/255.0 alpha:1].CGColor]; [txt_password.layer setBorderWidth:1.0f]; [txt_password.layer setShadowOpacity:0.0]; [txt_password.layer setMasksToBounds:YES]; // make round corners for txtfield CAShapeLayer *passwordMaskLayer = [[CAShapeLayer alloc] init]; UIBezierPath *passwordMaskPathWithRadiusTop = [UIBezierPath bezierPathWithRoundedRect:txt_password.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) cornerRadii:CGSizeMake(5.0, 5.0)]; passwordMaskLayer.frame = txt_password.bounds; passwordMaskLayer.path = passwordMaskPathWithRadiusTop.CGPath; passwordMaskLayer.fillColor = [UIColor whiteColor].CGColor; [txt_password.layer.mask setMask:passwordMaskLayer]; // add txtfield to view [self.view addSubview:txt_password]; return self; } 

该行:

 [txt_password.layer.mask setMask:passwordMaskLayer]; 

应该:

 [txt_password.layer setMask:passwordMaskLayer]; 

你可以试试这个。 我希望这有帮助。

 -(void)CustomizeTextField:(UITextField *)myTextField { CGRect rect = myTextField.bounds; UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:UIRectCornerTopLeft |UIRectCornerTopRight cornerRadii:CGSizeMake(6.0, 6.0)]; CAShapeLayer *layers = [CAShapeLayer layer]; layers.frame = rect; layers.path = path.CGPath; myTextField.layer.mask = layers; }