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

來源:互聯網
上載者:User

標籤:

一、設定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 表示輸入的是第一個字元

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.