Swift—UITextView的常见用法
https://www.jianshu.com/p/deb3e9e1f10c
2017.03.14 10:31* 字数 144 阅读 1320评论 0喜欢 2
1、UITextView的创建及基本属性设置#####
//创建UITextView对象
textView = UITextView(frame:CGRectMake(10.0, 120.0, 300.0, 200.0))
//背景颜色设置
textView.backgroundColor = UIColor.grayColor()
//添加到视图上
self.view.addSubview(textView)
//设置textview里面的字体颜色
textView.textColor = UIColor.greenColor()
//设置文本字体
textView.font = UIFont.systemFontOfSize(18);//使用系统默认字体,指定14号字号
textView.font = UIFont(name: "Helvetica-Bold", size: 18)//指定字体,指定字号
//设置它的背景颜色
textView.backgroundColor = UIColor.grayColor()
//设置显示内容
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
}
//文本视图设置圆角
textView.layer.cornerRadius = 20
textView.layer.masksToBounds = true
//是否允许点击链接和附件
textView.isSelectable = false
textView.isSelectable = true
//是否允许进行编辑
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
//给文字中的网址和电话号码自动加上链接
textView.dataDetectorTypes = [] //都不加
textView.dataDetectorTypes = .phoneNumber //只有电话号码加
textView.dataDetectorTypes = .link //只有网址加
textView.dataDetectorTypes = .all //电话和网址都加
//自适应高度
textView.autoresizingMask = UIViewAutoresizing.FlexibleHeight
//设置富文本
var attributeString:NSMutableAttributedString=NSMutableAttributedString(string: "经常听到,押金不退,晚一天交房租,被讹了。网上报价不真实?经常被忽悠")
//设置字体颜色
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))
//设置字体颜色
attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor.whiteColor(), range: NSMakeRange(0, 3))
//设置文字背景颜色
attributeString.addAttribute(NSBackgroundColorAttributeName, value: UIColor.orangeColor(), range: NSMakeRange(3, 3))
//赋值富文本
textView.attributedText = attributeString
//选中一段文本
textView.becomeFirstResponder()
textView.selectedRange = NSMakeRange(30, 10)
//获取内容整体高度
var height:CGFloat = textView.contentSize.height
2、自定义菜单#####
//定义2个菜单选择
我们在看一些文档的时候,往往会出现这种情况,我们把手指长按这段文字或者图片...会弹出一个按钮选择菜单,比如:复制,粘贴等我们可以进行一些列的操作,我们可以在这个菜单上加上一些别的东西,例如:分享,邮件,微信等。
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]
实现效果如下图:
3、代理设置和一些相关方法的实现#####
textView.delegate = self //指定代理对象
我们可以添加通知来监测UITextField所对应的不同的编辑状态
主要有以下状态:
UIKIT_EXTERN NSNotificationName const UITextViewTextDidBeginEditingNotification;
UIKIT_EXTERN NSNotificationName const UITextViewTextDidChangeNotification;
UIKIT_EXTERN NSNotificationName const UITextViewTextDidEndEditingNotification;
其对应的通知添加为:
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)
我们多制定对象实现了UITextViewDelegate并作为UITextView的代理就可以实现其所对应代理方法:
func textViewDidBeginEditing(_ textView: UITextView) {
//开始编辑时候出发
}
func textViewDidEndEditing(_ textView: UITextView) {
//结束编辑时候出发
}
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
return true //如果返回false,文本视图不能编辑
}
func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
return true //如果返回false,表示编辑结束之后,文本视图不可再编辑
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
//文本视图内容改变时,触发本方法,如果是回车符号,则textView释放第一响应值,返回false
if (text == "\n") {
textView.resignFirstResponder()
return false;
}
return true
}
func textViewDidChange(_ textView: UITextView) {
//文本视图改变后触发本代理方法
}
func textViewDidChangeSelection(_ textView: UITextView) {
//文本视图 改变选择内容,触发本代理方法
}
func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool
{
//链接在文本中显示。当链接被点击的时候,会触发本代理方法
return true
}
func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
//文本视图允许提供文本附件,文本附件点击时,会触发本代理方法 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; //不显示系统的菜单,改成true对比一下效果
}
//分享到微信
func shareWXMenu(sender: AnyObject?)
{
if textView.selectedRange.length > 0 {
println((textView.text as NSString).substringWithRange(textView.selectedRange))
}
println("这里实现 分享到微信 功能")
}
//分享到微博
func shareWBMenu(sender: AnyObject?)
{
println("这里实现 分享到微博 功能")
}
1,多行文本控件的创建
textView.frame = CGRect(x:50,y:180,width:self.view.bounds.size.width - 100,height:50)
textview.layer.borderWidth=1 //边框粗细
textview.layer.borderColor=UIColor.red.cgColor //边框颜色
self.view.addSubview(textview)
2,是否可编辑
textview.editable=false
3,内容是否可选
textview.selectable=false
4,属性font设置字体,textColor设置字体颜色,textAlignment设置对齐方式
textView.textColor = UIColor.red//设置字体颜色
textView.textAlignment = .center //设置对齐方式
5,给文字中的电话号码和网址自动加链接
textview.dataDetectorTypes = .none //都不加链接
textview.dataDetectorTypes = .phoneNumber //只有电话加链接
textview.dataDetectorTypes = .link //只有网址加链接
textview.dataDetectorTypes = .all //全部都加
textview.dataDetectorTypes = .calendarEvent //日历
textview.dataDetectorTypes = .shipmentTrackingNumber //货单号
textview.dataDetectorTypes = .flightNumber //班机号
textview.dataDetectorTypes = .lookupSuggestion //查看建议
6,自定义选择内容后的菜单
1、定义方法
let mail = UIMenuItem(title: "邮件", action: #selector(ViewController.onMail))
let weixin = UIMenuItem(title: "微信", action: #selector(ViewController.onWeiXin))
let menu = UIMenuController()
menu.menuItems = [mail,weixin]
注:这个方法仿照着写出来以后,会报警告,但是不影响使用
2、方法的实现
func onMail() {
print("mail")
}
func onWeiXin() {
print("weixin")
}