UITextfield uneditable field
我希望在其中包含不可编辑的常量文本的文本字段,例如:
1 | ENTER YOUR NAME: |
点击文本字段会在
之后获得光标
用户也不能删除或编辑"ENTER YOUR NAME:"。
我该如何实现呢?
将文本字段的委托设置为
1 2 3 4 5 6 7 | - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { //"ENTER YOUR NAME:" occupies the first 16 characters; if the user us trying // to change something that is within that 16-character range, say"NO" if (range.location < 16) return NO; ... check additional conditions here return YES; } |
我认为没有办法直接放置光标,但您可以在初始文本的尾随冒号后进行空选择,如本答案中所述。
一种解决方案是检查您的静态内容(静态文本)是否仍然存在,如果不存在,则在 shouldChangeCharactersInRange 中返回 NO。这是一个示例
1 2 3 4 5 6 7 8 9 10 11 | - (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSRange prefixRange = [textField.text rangeOfString:@"ENTER YOUR NAME:"]; if(suffixRange.location == NSNotFound) { return NO; } // Only characters in the NSCharacterSet you choose will insertable. NSCharacterSet *invalidCharSet = [[NSCharacterSet characterSetWithCharactersInString:ALPHA] invertedSet]; NSString *filtered = [[string componentsSeparatedByCharactersInSet:invalidCharSet] componentsJoinedByString:@""]; return [string isEqualToString:filtered]; } |
阿尔法是
#define ALPHA @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
我设法以一种有点棘手但简单的方式完成了它。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | UIButton *rem = [UIButton buttonWithType:UIButtonTypeCustom]; rem.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft; rem.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0); rem.frame = CGRectMake(0.0f, 210.0f, 300.0f, 40.0f); [rem setTitle:@"*X1*" forState:UIControlStateNormal]; CALayer * layer1 = [rem layer]; [layer1 setMasksToBounds:YES]; [layer1 setCornerRadius:8.0]; [layer1 setBorderWidth:0.0]; [layer1 setBorderColor:[[UIColor grayColor] CGColor]]; rem.backgroundColor = [UIColor colorWithPatternImage:image]; rem.titleLabel.font = [UIFont systemFontOfSize:17.0f]; rem.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; textField = [[UITextField alloc] initWithFrame:CGRectMake(45.0f, 210.0f, 255.0f, 40.0f)]; textField.backgroundColor = [UIColor clearColor]; [_textFields addObject:textField]; [textField setBorderStyle:(UITextBorderStyleNone)]; textField.textColor = [UIColor whiteColor]; [TableControll.view addSubview:rem]; [TableControll.view addSubview:textField]; |
基本上我只是创建标题为 UNEDITABLE NAME 的按钮,其大小是理想
我没有足够的声誉,或者我只是发表评论,但 Omar 的建议是使用 UILabel,在你的情况下会说"输入你的名字:",然后将你的 UITextField 放在远离那个标签,你想控制光标的位置。
为了让它看起来更漂亮,你可以放一些背景文本字段样式的图像(我就是这样做的),或者将 UILabel 的默认背景拉伸到所需的长度,然后确保 UITextField 的子视图位于标签的上方。