Swift5.0 UITexview的基本使用

  let texviewMy = UITextView.init()
    texviewMy.delegate = self;
    texviewMy.frame = CGRect(x: 100, y: 100, width: 200, height: 100)
    self.view .addSubview(texviewMy)
    texviewMy.backgroundColor = .red
    texviewMy.text = "我是一张eef"

    //设置字体
    texviewMy.font = UIFont.systemFont(ofSize: 13)
    //指定字体,指定字号
    texviewMy.font = UIFont(name: "Helvetica-Bold", size: 16)
    
    texviewMy.textAlignment = .left
    
    //是否允许点击链接和附件
    
    texviewMy.isSelectable = true
    
    //是否允许进行编辑
    texviewMy.isEditable = true
    
    //返回键的样式
    texviewMy.returnKeyType = UIReturnKeyType.done
    
    //弹出的键盘类型
    texviewMy.keyboardType = UIKeyboardType.default
    
    //设置是否可以滚动
    texviewMy.isScrollEnabled = true
    
    //给文字中的网址和电话号码自动加上链接
    texviewMy.dataDetectorTypes = []  //都不加
  //  texviewMy.dataDetectorTypes = .phoneNumber //只有电话号码加
  // texviewMy.dataDetectorTypes = .link //只有网址加
// texviewMy.dataDetectorTypes = .all  //电话和网址都加

    //自动适应高度
    texviewMy.autoresizingMask = UIView.AutoresizingMask.flexibleHeight
    
     //UITextView的富文本设置        
    let attributeStrig : NSMutableAttributedString = NSMutableAttributedString(string: "我是一条富文本呀")
          print("字符串的长度\(texviewMy.text.count)")
attributeStrig.addAttribute(NSMutableAttributedString.Key.foregroundColor, value: UIColor.white, range: NSMakeRange(1, 3))

    attributeStrig.addAttribute(NSMutableAttributedString.Key.font, value: UIFont.boldSystemFont(ofSize: 18), range: NSMakeRange(0, texviewMy.text.count))

    texviewMy.attributedText  = attributeStrig

//UITexview的代理方法的使用

// MARK: - UItexview代理方法

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
}

你可能感兴趣的:(Swift5.0 UITexview的基本使用)