ios 貼上或單個字元輸入 字數控制
一、UITextView
1. 在@interface中宣告代理
@interface MyViewController : UIViewController <UITextViewDelegate>
2. 設定UITexView的delegate,可以在viewDidLoad方法中實現,也可以在nib檔案(或是storyboard)中實現。
textView.delegate = self;
3. 實現代理方法。
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
textLabel.hidden =YES;
NSString *string = [textView.text stringByReplacingCharactersInRange:range withString:text];
if ([string length] >= 250)
{
string = [string substringToIndex:250];
textView.text = string;
CharNumber2.text =[NSString stringWithFormat:@"不可以輸入更多"];
return NO;
CharNumber2.text =[NSString stringWithFormat:@"你還可以輸入%d字",250 - string.length];
if ([string length] == 0)
{
textLabel.hidden = NO;
}
else if ([string length] > 0 && [string length] < 250)
{
}
}
if ([text isEqualToString:@"\n"])
{
[self fankui];return NO;
}return YES;
}
二、UITextField
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == self.titleTextField) {
NSString *string0 = [textField.text
if ([string0 length] > 30)
{
string0 = [string0 substringToIndex:30];
self.titleTextField.text = string0;
self.titleNumLabel.text = [NSString stringWithFormat:@"%d/30",string0.length];
self.titleNumLabel.textColor = kUIColorFromRGB(0xb7babb);
return NO;
}else{
self.titleNumLabel.text = [NSString stringWithFormat:@"%d/30",string0.length];
if (string0.length < 6 || string0.length > 30) {
self.titleNumLabel.textColor = [UIColor redColor];
}else{
self.titleNumLabel.textColor = kUIColorFromRGB(0xb7babb);
}
}
}
return YES;
}