iOS經典講解之妙用UITextView
阿新 • • 發佈:2019-01-23
// 新增textView - (void)addTextView { //UITextView可以使用父類的初始化方法initWithFrame:也可使用iOS7.0出現的自己獨有的的初始化方法initWithFrame:textContainer: //textContainer:是text接受者 可以為nil // 講解如果使用initWithFrame:textContainer:初始化方法需要注意的問題 // 這裡先講解三種類的關係: //1、NSTextStorage儲存並管理UITextView顯示的文字資訊,並且可以靈活的修改文字屬性 //2、NSLayoutManager用於管理NSTextStorage中文字內容的排版佈局 //3、NSTextContainer定義一個矩形區域用於存放已經進行了排版並設定好屬性的文字 // 使三者建立聯絡:必須建立三者聯絡,否則用該初始化方法文字不顯示 //建立container NSTextContainer *container = [[NSTextContainer alloc] initWithSize:CGSizeMake(100, 100)]; container.widthTracksTextView = YES; //建立layoutManager並新增container NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init]; [layoutManager addTextContainer:container]; //建立storage並新增layoutManager NSTextStorage *storage = [[NSTextStorage alloc] init]; [storage addLayoutManager:layoutManager]; /** 來向UITextStorage類或其子類傳送開始或完成文字編輯的訊息。在[storage beginEditing], [storage endEditing];兩條語句之間進行相應的文字編輯設計文字的樣式 [storage beginEditing]; NSDictionary *attrsDic = @{NSTextEffectAttributeName: NSTextEffectLetterpressStyle}; UIKIT_EXTERN NSString *const NSTextEffectAttributeName NS_AVAILABLE_IOS(7_0); // NSString, default nil: no text effect NSMutableAttributedString *mutableAttrString = [[NSMutableAttributedString alloc] initWithString:@"Letterpress" attributes:attrsDic]; NSAttributedString *appendAttrString = [[NSAttributedString alloc] initWithString:@" Append:Letterpress"]; [mutableAttrString appendAttributedString:appendAttrString]; [storage setAttributedString:mutableAttrString]; [storage endEditing]; */ // 最後在初始化方法中新增container //UITextView繼承於UIScrollView繼承父類的所有屬性和方法,這裡只介紹經常使用的方法和屬性支援多行輸入 UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(100, 100, 200, 100) textContainer:container]; // 設定背景顏色 textView.backgroundColor = [UIColor whiteColor]; // 設定字型顏色 textView.textColor = [UIColor blackColor]; // 設定字型和大小 textView.font = [UIFont fontWithName:@"Heiti TC" size:16]; // 設定內容 textView.text = @"輸入內容"; // 設定彈出鍵盤型別 textView.keyboardType = UIKeyboardTypeDefault; //設定鍵盤返回鍵的樣式 textView.returnKeyType = UIReturnKeyNext; // 設定是否允許滑動 textView.scrollEnabled = NO; // 是否顯示滑動條 textView.showsVerticalScrollIndicator = YES; // 設定代理 遵循代理 UITextViewDelegate textView.delegate = self; [self.view addSubview:textView]; } #pragma mark ---代理方法--- -(void)textViewDidBeginEditing:(UITextView *)textView { NSLog(@"開始編輯觸發"); } - (void)textViewDidEndEditing:(UITextView *)textView { NSLog(@"結束編輯觸發"); } -(BOOL)textViewShouldBeginEditing:(UITextView *)textView { NSLog(@"將要編輯觸發"); return YES; } -(BOOL)textViewShouldEndEditing:(UITextView *)textView { NSLog(@"將要結束編輯觸發"); return YES; } // 在編輯範圍是否允許輸入某些text // 如果你的textView裡面不允許用回車,可以用此方法通過按回車回收鍵盤 -(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { if ([text isEqualToString:@"\n"]) { [textView resignFirstResponder]; return NO; } else { return YES; } }