1、UITextView的創(chuàng)建及基本屬性設(shè)置#####
//創(chuàng)建UITextView對象
textView = UITextView(frame:CGRectMake(10.0, 120.0, 300.0, 200.0))
//背景顏色設(shè)置
textView.backgroundColor = UIColor.grayColor()
//添加到視圖上
self.view.addSubview(textView)
//設(shè)置textview里面的字體顏色
textView.textColor = UIColor.greenColor()
//設(shè)置文本字體
textView.font = UIFont.systemFontOfSize(18);//使用系統(tǒng)默認(rèn)字體,指定14號字號
textView.font = UIFont(name: "Helvetica-Bold", size: 18)//指定字體,指定字號
//設(shè)置它的背景顏色
textView.backgroundColor = UIColor.grayColor()
//設(shè)置顯示內(nèi)容
textView.text ="哈嘍,大家好,我是見哥"
//文本對齊方式
textView.textAlignment = .left
其中UITextField的文本的對齊方式有:
public enum NSTextAlignment : Int {
case left // Visually left aligned
case center // Visually centered
case right // Visually right aligned
/* !TARGET_OS_IPHONE */
// Visually right aligned
// Visually centered
case justified // Fully-justified. The last line in a paragraph is natural-aligned.
case natural // Indicates the default alignment for script
}
//文本視圖設(shè)置圓角
textView.layer.cornerRadius = 20
textView.layer.masksToBounds = true
//是否允許點擊鏈接和附件
textView.isSelectable = false
textView.isSelectable = true
//是否允許進(jìn)行編輯
textview.isEditable = false
textview.isEditable = true
//返回鍵的類型
textView.returnKeyType = UIReturnKeyType.Done
鍵盤的返回鍵類型:
public enum UIReturnKeyType : Int {
case `default`
case go
case google
case join
case next
case route
case search
case send
case yahoo
case done
case emergencyCall
@available(iOS 9.0, *)
case `continue`
}
//鍵盤類型
textView.keyboardType = UIKeyboardType.Default
鍵盤的類型也是比較多的
public enum UIKeyboardType : Int {
case `default` // Default type for the current input method.
case asciiCapable // Displays a keyboard which can enter ASCII characters
case numbersAndPunctuation // Numbers and assorted punctuation.
case URL // A type optimized for URL entry (shows . / .com prominently).
case numberPad // A number pad with locale-appropriate digits (0-9, ?-?, ?-?, etc.). Suitable for PIN entry.
case phonePad // A phone pad (1-9, *, 0, #, with letters under the numbers).
case namePhonePad // A type optimized for entering a person's name or phone number.
case emailAddress // A type optimized for multiple email address entry (shows space @ . prominently).
@available(iOS 4.1, *)
case decimalPad // A number pad with a decimal point.
@available(iOS 5.0, *)
case twitter // A type optimized for twitter text entry (easy access to @ #)
@available(iOS 7.0, *)
case webSearch // A default keyboard type with URL-oriented addition (shows space . prominently).
@available(iOS 10.0, *)
case asciiCapableNumberPad // A number pad (0-9) that will always be ASCII digits.
public static var alphabet: UIKeyboardType { get } // Deprecated
}
//是否可以滾動
textView.scrollEnabled = true
//給文字中的網(wǎng)址和電話號碼自動加上鏈接
textView.dataDetectorTypes = [] //都不加
textView.dataDetectorTypes = .phoneNumber //只有電話號碼加
textView.dataDetectorTypes = .link //只有網(wǎng)址加
textView.dataDetectorTypes = .all //電話和網(wǎng)址都加
//自適應(yīng)高度
textView.autoresizingMask = UIViewAutoresizing.FlexibleHeight
//設(shè)置富文本
var attributeString:NSMutableAttributedString=NSMutableAttributedString(string: "經(jīng)常聽到,押金不退,晚一天交房租,被訛了。網(wǎng)上報價不真實?經(jīng)常被忽悠")
//設(shè)置字體顏色
attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSMakeRange(0, attributeString.length))
//文本所有字符字體HelveticaNeue-Bold,16號
attributeString.addAttribute(NSFontAttributeName, value: UIFont(name: "HelveticaNeue-Bold", size: 16)!, range: NSMakeRange(0, attributeString.length))
//文本0開始5個字符字體HelveticaNeue-Bold,16號
attributeString.addAttribute(NSFontAttributeName, value: UIFont(name: "HelveticaNeue-Bold", size: 26)!, range: NSMakeRange(0, 5))
//設(shè)置字體顏色
attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor.whiteColor(), range: NSMakeRange(0, 3))
//設(shè)置文字背景顏色
attributeString.addAttribute(NSBackgroundColorAttributeName, value: UIColor.orangeColor(), range: NSMakeRange(3, 3))
//賦值富文本
textView.attributedText = attributeString
//選中一段文本
textView.becomeFirstResponder()
textView.selectedRange = NSMakeRange(30, 10)
//獲取內(nèi)容整體高度
var height:CGFloat = textView.contentSize.height
2、自定義菜單#####
//定義2個菜單選擇
我們在看一些文檔的時候,往往會出現(xiàn)這種情況,我們把手指長按這段文字或者圖片...會彈出一個按鈕選擇菜單,比如:復(fù)制,粘貼等我們可以進(jìn)行一些列的操作,我們可以在這個菜單上加上一些別的東西,例如:分享,郵件,微信等。
var menuItem1:UIMenuItem = UIMenuItem(title: "分享到微信", action: "shareWXMenu:")
var menuItem2:UIMenuItem = UIMenuItem(title: "分享到微博", action: "shareWBMenu:")
var menuController:UIMenuController = UIMenuController.sharedMenuController()
menuController.menuItems = [menuItem1,menuItem2]
//或者
//let mail = UIMenuItem(title: "郵件", action: #selector(ViewController.onMail))
//let weixin = UIMenuItem(title: "微信", action: #selector(ViewController.onWeiXin))
//let menu = UIMenuController()
//menu.menuItems = [mail,weixin]
實現(xiàn)效果如下圖:

3、代理設(shè)置和一些相關(guān)方法的實現(xiàn)#####
textView.delegate = self //指定代理對象
我們可以添加通知來監(jiān)測UITextField所對應(yīng)的不同的編輯狀態(tài)
主要有以下狀態(tài):
UIKIT_EXTERN NSNotificationName const UITextViewTextDidBeginEditingNotification;
UIKIT_EXTERN NSNotificationName const UITextViewTextDidChangeNotification;
UIKIT_EXTERN NSNotificationName const UITextViewTextDidEndEditingNotification;
其對應(yīng)的通知添加為:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidBeginEditing", name: UITextViewTextDidBeginEditingNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidEndEditing", name: UITextViewTextDidEndEditingNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChange", name: UITextViewTextDidChangeNotification, object: nil)
我們多制定對象實現(xiàn)了UITextViewDelegate并作為UITextView的代理就可以實現(xiàn)其所對應(yīng)代理方法:
func textViewDidBeginEditing(_ textView: UITextView) {
//開始編輯時候出發(fā)
}
func textViewDidEndEditing(_ textView: UITextView) {
//結(jié)束編輯時候出發(fā)
}
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
return true //如果返回false,文本視圖不能編輯
}
func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
return true //如果返回false,表示編輯結(jié)束之后,文本視圖不可再編輯
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
//文本視圖內(nèi)容改變時,觸發(fā)本方法,如果是回車符號,則textView釋放第一響應(yīng)值,返回false
if (text == "\n") {
textView.resignFirstResponder()
return false;
}
return true
}
func textViewDidChange(_ textView: UITextView) {
//文本視圖改變后觸發(fā)本代理方法
}
func textViewDidChangeSelection(_ textView: UITextView) {
//文本視圖 改變選擇內(nèi)容,觸發(fā)本代理方法
}
func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool
{
//鏈接在文本中顯示。當(dāng)鏈接被點擊的時候,會觸發(fā)本代理方法
return true
}
func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
//文本視圖允許提供文本附件,文本附件點擊時,會觸發(fā)本代理方法 return true
}
4、點擊選中文字彈出按鈕的顯示######
override func canPerformAction(action:Selector,withSender sender: AnyObject?) -> Bool {
//判斷有沒有選中文字,
//如果選擇,輸出選擇的文本
var isSelect:Bool = textView.selectedRange.length > 0
if(action == "shareWXMenu:" && isSelect)//選擇文本,并點擊分享到微信菜單
{
return true;
}
else if(action == "shareWBMenu:" && isSelect)//選擇文本,并點擊分享到微博菜單
{
return true;
}
return false; //不顯示系統(tǒng)的菜單,改成true對比一下效果
}
//分享到微信
func shareWXMenu(sender: AnyObject?)
{
if textView.selectedRange.length > 0 {
println((textView.text as NSString).substringWithRange(textView.selectedRange))
}
println("這里實現(xiàn) 分享到微信 功能")
}
//分享到微博
func shareWBMenu(sender: AnyObject?)
{
println("這里實現(xiàn) 分享到微博 功能")
}