[分享]iOS開發-剩餘可輸入多少個字+textView上的label偽裝成placeHolder

ShevaKuilin發表於2016-03-04
//剩餘可輸入多少個字+textView上的label偽裝成placeHolder
-(void)textViewDidChange:(UITextView *)textView{
NSInteger inputLength = 40 - self.textView.text.length;    
NSString * remainder = [NSString stringWithFormat:@"剩餘輸入%@字", @(inputLength)];    
NSMutableAttributedString * attString = [[NSMutableAttributedString alloc] initWithString:remainder];    
[attString addAttributes:@{NSForegroundColorAttributeName:[UIColor redColor], NSFontAttributeName:MyFont(14)} range:[remainder rangeOfString:[NSString stringWithFormat:@"%@", @(inputLength)]]];    
self.changeLabel.attributedText = attString;
 }
 
-(IBAction)touchOther:(UIControl *)sender {    
[self.textView resignFirstResponder];
 }
 
-(void)textViewDidEndEditing:(UITextView *)textView{   
 [self.view endEditing:YES];    
if (self.textView.text.length > 0) {        
self.promptLabel.hidden = YES;   
 } else {        
    self.promptLabel.hidden = NO;    
}
}

-(void)textViewDidBeginEditing:(UITextView *)textView{    
  self.promptLabel.hidden = YES;  

 }

//其實還有更好的方式,是在-(void)textViewDidChange:(UITextView *)textView中進行判斷是否隱藏,關於這一類的偽裝placeHolder,儘量都用label來進行,不要直接選擇對textView本身的text進行操作

//超出textField限制範圍時的label實時顯示
NSString * remainder = [NSString stringWithFormat:@"已超出限定範圍%@字", @(labs(inputLength))];
NSMutableAttributedString * attString = [[NSMutableAttributedString alloc] initWithString:remainder];
[attString addAttributes:@{NSForegroundColorAttributeName:[UIColor redColor], NSFontAttributeName:MyFont(14)} range:[remainder rangeOfString:[NSString stringWithFormat:@"%@", @(labs(inputLength))]]];
self.changeLabel.attributedText = attString;

相關文章