UITextField仅在顶部有圆角

时间:2014-05-06 20:42:27

标签: ios objective-c uitextfield

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

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

我现在已经搞好几个小时了,我已经阅读了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;
}

2 个答案:

答案 0 :(得分:5)

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

-(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;
}

答案 1 :(得分:5)

该行:

[txt_password.layer.mask setMask:passwordMaskLayer];

应该是:

[txt_password.layer setMask:passwordMaskLayer];