1.創(chuàng)建一個帶邊框的UITextView
override func viewDidLoad() {
super.viewDidLoad()
//定義控件x:30 y:100 width:300 height:40
let textView = UITextView(frame: CGRect(x: 30, y: 100, width: 300, height: 40))
self.view.addSubview(textView)
textView.layer.borderWidth = 1//邊框?qū)挾? textView.layer.borderColor = UIColor.black.cgColor//邊框顏色
textView.text = "這是一個黑邊框的UITextView"http://設(shè)置文本內(nèi)容
}
普通定義
2.設(shè)置字體font屬性宋列,字體顏色textColor昭抒,對齊方式textAlignment
textView.font = UIFont.boldSystemFont(ofSize: 12)//設(shè)置字體font屬性
textView.textColor = UIColor.red//設(shè)置字體顏色
textView.textAlignment = .center//設(shè)置內(nèi)容對齊方式
設(shè)置屬性
3.設(shè)置是否可編輯,內(nèi)容是否可選
textView.isEditable = false//textView不可編輯
textView.isSelectable = true//內(nèi)容可選
運行效果如下圖所示:內(nèi)容可選
4.給文字中的電話號碼和網(wǎng)址自動加鏈接
textView.dataDetectorTypes = [] //都不加鏈接
textView.dataDetectorTypes = UIDataDetectorTypes.phoneNumber //只有電話加鏈接
textView.dataDetectorTypes = UIDataDetectorTypes.link //只有網(wǎng)址加鏈接
textView.dataDetectorTypes = UIDataDetectorTypes.all //電話和網(wǎng)址都加
要實現(xiàn)添加鏈接首先需要將textview設(shè)置為不可編輯狀態(tài)炼杖,例如:
textView.isEditable = false//textView不可編輯
textView.dataDetectorTypes = .all//設(shè)置鏈接類型
textView.text = "phone:13859222222,\n link:https://www.baidu.com"http://設(shè)置文本內(nèi)容
link.gif
5.自定義選擇菜單
常常我們在選擇完內(nèi)容之后除復(fù)制灭返,剪切還可以做一些特殊的操作,比如分享到微信之類的社交媒體上坤邪,下面我們舉一個自定義選擇菜單的簡單例子
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//定義控件x:30 y:100 width:300 height:40
let textView = UITextView(frame: CGRect(x: 30, y: 100, width: 300, height: self.view.bounds.height - 100))
self.view.addSubview(textView)
textView.layer.borderWidth = 1//邊框?qū)挾?
textView.layer.borderColor = UIColor.black.cgColor//邊框顏色
textView.font = UIFont.boldSystemFont(ofSize: 12)//設(shè)置字體font屬性
textView.textColor = UIColor.black//設(shè)置字體顏色
textView.textAlignment = .center//設(shè)置內(nèi)容對齊方式
textView.isSelectable = true//內(nèi)容可選
textView.isEditable = true//textView不可編輯
textView.dataDetectorTypes = .all//設(shè)置鏈接類型
textView.text = "從明天起熙含,做一個幸福的人\n喂馬,劈柴艇纺,周游世界\n從明天起怎静,關(guān)心糧食和蔬菜\n我有一所房子,面朝大海黔衡,春暖花開\n從明天起蚓聘,和每一個親人通信\n告訴他們我的幸福\n那幸福的閃電告訴我的\n我將告訴每一個人\n給每一條河每一座山取一個溫暖的名字"http://設(shè)置文本內(nèi)容
let wx = UIMenuItem(title: "微信", action: #selector(openWX))
let menu = UIMenuController()
menu.menuItems = [wx]
}
@objc func openWX(){
print("打開微信")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
運行效果如下圖所示:自定義選擇菜單
文章只是講解了UITextView最基礎(chǔ)的用法,怎么樣通過自定義選擇菜單實現(xiàn)將選擇的內(nèi)容分享到微信盟劫,有興趣的小伙伴可以自行去查一查資料