Cursor appears before customized UITextField backg

2019-07-07 05:52发布

问题:

I have a background image of size 360X44 which I am trying to put as the background of my UITextFields however it is showing an unexpected behaviour. The cursor is getting appeared before the image starts but the texts getting written on the write place.

Implementation of my UiTextField

UITextField *textFieldRounded = [[UITextField alloc] initWithFrame:CGRectMake(100, 75, 215, 30)];
textFieldRounded.borderStyle = UITextBorderStyleNone;
UIImage *fieldBGImage = [[UIImage imageNamed:@"textfield_normal.png"]  stretchableImageWithLeftCapWidth:50 topCapHeight:50];
[textFieldRounded setBackground:fieldBGImage];
textFieldRounded.textColor = [UIColor blackColor];
textFieldRounded.font = [UIFont systemFontOfSize:17.0];
textFieldRounded.placeholder = @"http://";  //place holder
textFieldRounded.backgroundColor = [UIColor whiteColor];
textFieldRounded.autocorrectionType = UITextAutocorrectionTypeNo;
textFieldRounded.backgroundColor = [UIColor clearColor];
textFieldRounded.keyboardType = UIKeyboardTypeDefault;
textFieldRounded.returnKeyType = UIReturnKeyDone;
textFieldRounded.clearsOnBeginEditing = NO;
textFieldRounded.clearButtonMode = UITextFieldViewModeWhileEditing;    
[self.view addSubview:textFieldRounded];    
textFieldRounded.delegate = self;

回答1:

i just set TextFiled background Image like my bellow code And working Good:-

        [YourTextFiled setFont:[UIFont systemFontOfSize:18]];
        YourTextFiled.textAlignment = UITextAlignmentLeft;
        YourTextFiled.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 12, 20)];
        YourTextFiled.leftViewMode = UITextFieldViewModeAlways;
        YourTextFiled.background = [[UIImage imageNamed:@"xFOEr.png"] stretchableImageWithLeftCapWidth:7 topCapHeight:17];

looking like"-



回答2:

I'd suggest instead of adding image as a background color. Add it as a different component. i.e. First add a UIImageView and then add your UITextField on it.

In the mean time try to make this change in your current code :

UITextField *textFieldRounded = [[UITextField alloc] initWithFrame:CGRectMake(100, 75, 360, 44)];


回答3:

UITextView *textView = [[UITextView alloc]initWithFrame: window.frame];
textView.text = @"text\n text\n text";
UIImageView *imgView = [[UIImageView alloc]initWithFrame: textView.frame];
imgView.image = [UIImage imageNamed: @"myImage.jpg"];
[textView addSubview: imgView];
[textView sendSubviewToBack: imgView];
[window addSubview: textView];

Dont use background property. Add image as subview and send subview to back.