Swift - 多行文本输入框(UITextView)的用法

(本文代码已升级至Swift4)

1、多行文本控件的创建

let textview = UITextView(frame:CGRect(x:10, y:100, width:200, height:100))
textview.layer.borderWidth = 1  //边框粗细
textview.layer.borderColor = UIColor.gray.cgColor //边框颜色
self.view.addSubview(textview)

2、是否可编辑

textview.isEditable = false

3、内容是否可选

textview.isSelectable = false

4、属性font设置字体,textColor设置字体颜色,textAlignment设置对齐方式

5、给文字中的电话号码和网址自动加链接

textview.dataDetectorTypes = [] //都不加链接
textview.dataDetectorTypes = UIDataDetectorTypes.phoneNumber //只有电话加链接
textview.dataDetectorTypes = UIDataDetectorTypes.link //只有网址加链接
textview.dataDetectorTypes = UIDataDetectorTypes.all //电话和网址都加

6、自定义选择内容后的菜单 \@
我们在看新闻或小说的时候,常常在点选文字后会弹出菜单进行选择,复制等操作。我们可以在这个菜单上添加一些其他内容,如加上“邮件”“微信”等按钮选项

image.png
import UIKit
 
class ViewController: UIViewController {
     
    override func viewDidLoad() {
        super.viewDidLoad()
         
        let textview = UITextView(frame:CGRect(x:10, y:100, width:200, height:100))
        textview.layer.borderWidth = 1  //边框粗细
        textview.layer.borderColor = UIColor.gray.cgColor //边框颜色
        self.view.addSubview(textview)
         
        let mail = UIMenuItem(title: "邮件", action: #selector(ViewController.onMail))
        let weixin = UIMenuItem(title: "微信", action: #selector(ViewController.onWeiXin))
        let menu = UIMenuController()
        menu.menuItems = [mail,weixin]
    }
     
    @objc func onMail(){
        print("mail")
    }
     
    @objc func onWeiXin(){
        print("weixin")
    }
     
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

原文出自:www.hangge.com 转载请保留原文链接:http://www.hangge.com/blog/cache/detail_531.html

你可能感兴趣的:(Swift - 多行文本输入框(UITextView)的用法)