iOS開發之UITextView,設置textView的行間距及placeholder

文章轉載自:http://www.cnblogs.com/daguo/p/4080512.html



一、設置textView的行間距

1.如果只是靜態顯示textView的內容爲設置的行間距,執行如下代碼:

//    textview 改變字體的行間距 
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; 
    paragraphStyle.lineSpacing = 10;// 字體的行間距 
     
    NSDictionary *attributes = @{ 
                                 NSFontAttributeName:[UIFont systemFontOfSize:15], 
                                 NSParagraphStyleAttributeName:paragraphStyle 
                                 }; 
    textView.attributedText = [[NSAttributedString alloc] initWithString:@"輸入你的內容" attributes:attributes];

 

2.如果是想在輸入內容的時候就按照設置的行間距進行動態改變,那就需要將上面代碼放到textView的delegate方法裏

-(void)textViewDidChange:(UITextView *)textView

{

    //    textview 改變字體的行間距

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];

    paragraphStyle.lineSpacing = 20;// 字體的行間距

    

    NSDictionary *attributes = @{

                                 NSFontAttributeName:[UIFont systemFontOfSize:15],

                                 NSParagraphStyleAttributeName:paragraphStyle

                                 };

    textView.attributedText = [[NSAttributedString alloc] initWithString:textView.text attributes:attributes];

 

}

 

一、設置textView的placeholder

    UITextView上如何加上類似於UITextField的placeholder呢,其實在UITextView上加上一個UILabel或者UITextView,如果用UILable的話,會出現一個問題就是當placeholder的文字過長導致換行的時候就會出現問題,而用UITextView則可以有效避免此問題。

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

{    if (![text isEqualToString:@""])

        {

            _placeholderLabel.hidden = YES;

        }

     if ([text isEqualToString:@""] && range.location == 0 && range.length == 1)

        {

            _placeholderLabel.hidden = NO;

        }

    return YES;

}

 

說明如下:

  (1) _placeholderLabel 是加在UITextView後面的UITextView,_placeholderLabel要保證和真正的輸入框的設置一樣,字體設置成淺灰色,然後[_placeholderLabel setEditable:NO];真正的輸入框要設置背景色透明,保證能看到底部的_placeholderLabel。

    (2) [text isEqualToString:@""] 表示輸入的是退格鍵

    (3) range.location == 0 && range.length == 1 表示輸入的是第一個字符


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章