首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

UITextView 粘貼長文本報錯?換行符轉義與屬性設置全解析

     編輯:程式設計綜合問答

現象

txtView.text = @"About us myventr.co is a web-based tool ... very long string ...";
// 編譯報錯或運行時截斷

根因

  1. 字符串字面量過長:Objective-C 單行字符串字面量有長度限制(編譯器實現相關),超長需分行。
  2. 未轉義換行:源碼中直接換行會導致語法錯誤,需用 \n 或隱式拼接。
  3. 屬性設置錯誤:代碼寫成 txtView.txt,正確是 txtView.text。

正確寫法

// 方式一:隱式拼接(推薦,編譯器自動合併)
txtView.text = @"About us myventr.co is a web-based tool for event creation, "
               @"event searching and online ticket selling whilst also serving as a social media network. "
               @"myventr.co is not just about creating events and buying tickets online "
               @"but is also a place for you to socialise. "
               @"You can create your own profile, connect with friends or create your own group for your organisation! "
               @"How is this different to other social media websites then? "
               @"Myevent is about connecting people's social lives and events all at the same place. "
               @"myventr.co will help find all the event details around your location "
               @"and will also help avoid events clashing by simply searching the Event Calendar before creating an event.";

// 方式二:顯式 \n 換行(若需保留換行顯示)
txtView.text = @"Line 1\nLine 2\nLine 3";

// 方式三:從文件/網絡加載(超長文本最佳實踐)
NSString *path = [[NSBundle mainBundle] pathForResource:@"about" ofType:@"txt"];
txtView.text = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

顯示優化建議

  • txtView.editable = NO; 僅展示。
  • txtView.dataDetectorTypes = UIDataDetectorTypeAll; 自動識別鏈接/電話/日期。
  • txtView.textContainerInset = UIEdgeInsetsMake(16, 12, 16, 12); 內邊距提升閱讀體驗。
  • 極長文本(>10KB)考慮 UITextView + NSAttributedString 分頁加載或 WKWebView 渲染 HTML。

總結

長文本賦值:**隱式拼接字符串字面量** 或 **外部資源文件加載**,切勿單行硬寫。修正屬性名 .text,啟用數據檢測與內邊距,體驗即刻提升。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved