我想做一个UITextField,它有一个静态前缀,用户不能编辑或删除,同时也用浅灰色字体颜色.
文本字段的可编辑部分应始终以黑色显示.
下面给出一个例子:

它主要用于输入用户名,带有不断添加前缀的域.
我已经尝试过使用textFieldShouldClear和textField:shouldChangeCharactersInRange:replacementString:委托方法NSMutableAttributedString,但是根本无法解决它:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSMutableAttributedString *text = [textField.attributedText mutableCopy];
[text addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, 7)];
if (textField.text.length > 7)
{
[text addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(7, textField.attributedText.length - 7)];
}
[text addAttribute:NSFontAttributeName value:[UIFont gothamFontForSize:textField.font.pointSize andWeight:kGothamLight] range:NSMakeRange(0, textField.attributedText.length)];
return range.location > 6;
}
- (BOOL)textFieldShouldClear:(UITextField *)textField
{
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"kombit\\"];
[text addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, 7)];
[text addAttribute:NSFontAttributeName value:[UIFont gothamFontForSize:textField.font.pointSize andWeight:kGothamLight] …Run Code Online (Sandbox Code Playgroud)