-->

Creating custom UITextView with UILabels as well a

2020-07-21 03:19发布

问题:

I would like to create a custom UITextView with the ability to enter text in it, as well as programmatically adding some UILabels there that would act like text (I need to delete them with the 'backspace' button when the cursor comes near them).

This UITextView should be expandable and the labels can have different width.

Any ideas of how you can create this sort of thing, any tutorials or such?

回答1:

you can create textfield using this code.

UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 200, 300, 40)];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.font = [UIFont systemFontOfSize:15];
textField.placeholder = @"enter text";
textField.autocorrectionType = UITextAutocorrectionTypeNo;
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyDone;
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;    
textField.delegate = self;
[self.view addSubview:textField];
[textField release];

And for creating label you can use this code:

CGRect labelFrame = CGRectMake( 10, 40, 100, 30 );
    UILabel* label = [[UILabel alloc] initWithFrame: labelFrame];
    [label setText: @"My Label"];
    [label setTextColor: [UIColor orangeColor]];
    label.backgroundColor =[UIColor clearColor];
    [view addSubview: label];

and for deleting label when backspace tape use this method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if ([string isEqualToString:@""]) {
NSLog(@"backspace button pressed");
[label removeFromSuperview];
}
return YES;
}

If the backspace button is pressed, then the replacementString(string) will have null value. So we can identify backspace button press using this.