UITextView通常用來顯示大量的文本,當然了也是可以輸入編輯的跟UITextField作用差不多,但是也有一點區別。接下來先看代碼再細說:
func creatTextView() {
let textView = UITextView(frame: CGRectMake(10, 50, 250, 200))
textView.backgroundColor = UIColor.grayColor()
textView.delegate = self
//邊框顏色和邊框粗細
textView.layer.borderColor = UIColor.greenColor().CGColor
textView.layer.borderWidth = 2
//成爲第一響應者出現鍵盤
textView.becomeFirstResponder()
textView.returnKeyType = .Done
//鍵盤類型
// textView.keyboardType = .NumberPad
textView.textColor = UIColor.whiteColor()
textView.font = UIFont.systemFontOfSize(20)
//可以被發現的類型特殊數據入鏈接、電話號碼、日期......
textView.dataDetectorTypes = .All
// textView.dataDetectorTypes = .CalendarEvent
// textView.dataDetectorTypes = .Link
// textView.dataDetectorTypes = .PhoneNumber
textView.text = "亂起八糟一大堆,還不如行情風氣清平之飛馬。風起青萍之粉末就是鏈接https://www.baidu.com 聯繫號碼18868824465 日期2016/7/28"
textView.editable = false
self.view.addSubview(textView)
//選中菜單欄
let phone = UIMenuItem(title: "電話", action:#selector(call))
UIMenuController().menuItems=[phone]
}
使用這個屬性textView.becomeFirstResponder()
可以讓文本框出現的時候鍵盤就自動出現了,同時還可以指定鍵盤類型。textView的這個屬性dataDetectorTypes
是指textView可以自動識別一些特殊的文字內容比如說鏈接、電話號碼、日期等。要記住在一個textView中dataDetectorTypes屬性只能給一個值所以你如果需要同時識別多種內容要這樣:textView.dataDetectorTypes = .All
你沒辦法在指定識別鏈接和電話號碼的同時讓它不識別日期。如果你想dataDetectorTypes這個屬性生效還要指定這個textView是不可編輯的:textView.editable = false
當它是可以編輯的時候是不可以識別特定內容的。我們知道當按住文本框的內容時會有個選中菜單欄裏面有很多選項比如Cut Copy Replace Select 等等這些常見的東西,我們也是可以在這選中欄中添加自己的一個選項看代碼:
let phone = UIMenuItem(title: "電話", action:#selector(call))
UIMenuController().menuItems=[phone]
func call() {
print("選中了")
}
現在我們選中文字按電話這個選項就會在控制檯中打印文字的。
textView還是有一些代理方法的,這些方法同樣的可以監督我們編輯的文字的時期的:
//將要結束編輯
func textViewShouldEndEditing(textView: UITextView) -> Bool {
return true
}
//文本框結束編輯了
func textViewDidEndEditing(textView: UITextView) {
//放棄第一響應者,鍵盤消失
textView.resignFirstResponder()
}
//文本框被編輯了
func textViewDidChange(textView: UITextView) {
}
//監聽最後一個輸入的字符,如果是回車就收回鍵盤
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
if text == "\n" {
textView.resignFirstResponder()
return false
}
return true
}