Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何在UITextView中显示可单击链接_Ios_Swift_Uitextview - Fatal编程技术网

Ios 如何在UITextView中显示可单击链接

Ios 如何在UITextView中显示可单击链接,ios,swift,uitextview,Ios,Swift,Uitextview,我试图在UITextview中显示带有可单击链接的属性字符串。我已经创建了一个简单的测试项目,看看哪里出了问题,但仍然无法找出答案。我尝试过启用用户交互和设置shouldInteractWithURLs委托方法,但仍然不起作用。这是我的代码(对于只包含textview的视图控制器) 下面是我实现的委托方法: func textViewShouldBeginEditing(textView: UITextView) -> Bool { return false } func tex

我试图在UITextview中显示带有可单击链接的属性字符串。我已经创建了一个简单的测试项目,看看哪里出了问题,但仍然无法找出答案。我尝试过启用用户交互和设置shouldInteractWithURLs委托方法,但仍然不起作用。这是我的代码(对于只包含textview的视图控制器)

下面是我实现的委托方法:

func textViewShouldBeginEditing(textView: UITextView) -> Bool {
    return false
}

func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool {
    return true
}

这仍然不起作用。我已经搜索了这个主题,但没有任何帮助。非常感谢。

只需在情节提要中选择
UITextView
,然后转到“显示属性检查器”,然后选择
selectable
链接。如下图所示。确保未选中“可编辑”


Swift 3 iOS 10:这里有一个可点击的扩展UITextView,只要链接以www.exmaple.com开头,它就会自动检测textview中的网站。例如:www.exmaple.com如果它存在于文本中的任何地方,则可以点击。下面是课程:

import Foundation
import UIKit




public class ClickableTextView:UITextView{



    var tap:UITapGestureRecognizer!
    override public init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        print("init")
        setup()
    }
    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }


    func setup(){

        // Add tap gesture recognizer to Text View
        tap = UITapGestureRecognizer(target: self, action: #selector(self.myMethodToHandleTap(sender:)))
        //        tap.delegate = self
        self.addGestureRecognizer(tap)
    }

    func myMethodToHandleTap(sender: UITapGestureRecognizer){

        let myTextView = sender.view as! UITextView
        let layoutManager = myTextView.layoutManager

        // location of tap in myTextView coordinates and taking the inset into account
        var location = sender.location(in: myTextView)
        location.x -= myTextView.textContainerInset.left;
        location.y -= myTextView.textContainerInset.top;


        // character index at tap location
        let characterIndex = layoutManager.characterIndex(for: location, in: myTextView.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)

        // if index is valid then do something.
        if characterIndex < myTextView.textStorage.length {

            let orgString = myTextView.attributedText.string


            //Find the WWW
            var didFind = false
            var count:Int = characterIndex
            while(count > 2 && didFind == false){

                let myRange = NSRange(location: count-1, length: 2)
                let substring = (orgString as NSString).substring(with: myRange)

//                print(substring,count)

                if substring == " w" || (substring  == "w." && count == 3){
                    didFind = true
//                    print("Did find",count)

                    var count2 = count
                    while(count2 < orgString.characters.count){

                        let myRange = NSRange(location: count2 - 1, length: 2)
                        let substring = (orgString as NSString).substring(with: myRange)

//                        print("Did 2",count2,substring)
                        count2 += 1


                        //If it was at the end of textView
                        if count2  == orgString.characters.count {

                            let length = orgString.characters.count - count
                            let myRange = NSRange(location: count, length: length)

                            let substring = (orgString as NSString).substring(with: myRange)

                            openLink(link: substring)
                            print("It's a Link",substring)
                            return
                        }

                        //If it's in the middle

                        if substring.hasSuffix(" "){

                            let length =  count2 - count
                            let myRange = NSRange(location: count, length: length)

                            let substring = (orgString as NSString).substring(with: myRange)

                            openLink(link: substring)
                            print("It's a Link",substring)

                            return
                        }

                    }

                    return
                }


                if substring.hasPrefix(" "){

                    print("Not a link")
                    return
                }

                count -= 1

            }


        }


    }


    func openLink(link:String){

        if let checkURL = URL(string: "http://\(link.replacingOccurrences(of: " ", with: ""))") {
            if UIApplication.shared.canOpenURL(checkURL) {
                UIApplication.shared.open(checkURL, options: [:], completionHandler: nil)

                print("url successfully opened")
            }
        } else {
            print("invalid url")
        }
    }


    public override func didMoveToWindow() {
        if self.window == nil{
            self.removeGestureRecognizer(tap)
            print("ClickableTextView View removed from")
        }
    }
}
<代码>导入基础 导入UIKit 公共类ClickableTextView:UITextView{ var tap:UITapGestureRecognitor! 重写公共init(frame:CGRect,textContainer:NSTextContainer?){ super.init(frame:frame,textContainer:textContainer) 打印(“初始化”) 设置() } 所需的公共初始化?(编码者aDecoder:NSCoder){ super.init(编码者:aDecoder) 设置() } 函数设置(){ //将点击手势识别器添加到文本视图 tap=UITAPPgestureRecognitor(目标:self,操作:#选择器(self.myMethodToHandleTap(发送方:)) //tap.delegate=self self.addgestureignizer(点击) } func myMethodToHandleTap(发件人:UITapGestureRecognitizer){ 让myTextView=sender.view为!UITextView 让layoutManager=myTextView.layoutManager //点击在myTextView坐标中的位置,并考虑插入 var location=sender.location(在:myTextView中) location.x-=myTextView.TextContainerSet.left; location.y-=myTextView.TextContainerSet.top; //抽头位置的字符索引 让characterIndex=layoutManager.characterIndex(对于:位置,在:myTextView.textContainer中,插入点之间距离的分数:nil) //如果索引是有效的,那么做一些事情。 如果characterIndex2&&didFind==false){ 让myRange=NSRange(位置:count-1,长度:2) let substring=(orgString作为NSString)。substring(with:myRange) //打印(子字符串、计数) 如果子字符串==“w”| |(子字符串==“w.”&计数==3){ didFind=true //打印(“未找到”,计数) var count2=计数 while(count2适用于swift3.0

  override func viewDidLoad() {
     super.viewDidLoad()

  let linkAttributes = [
        NSLinkAttributeName: NSURL(string: "http://stalwartitsolution.co.in/luminutri_flow/terms-condition")!
        ] as [String : Any]
  let attributedString = NSMutableAttributedString(string: "Please tick box to confirm you agree to our Terms & Conditions, Privacy Policy, Disclaimer. ")

  attributedString.setAttributes(linkAttributes, range: NSMakeRange(44, 18))

  attributedString.addAttribute(NSUnderlineStyleAttributeName, value: NSNumber(value: 1), range: NSMakeRange(44, 18))

  textview.delegate = self
  textview.attributedText = attributedString
  textview.linkTextAttributes = [NSForegroundColorAttributeName: UIColor.red]
  textview.textColor = UIColor.white
  }


  func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
    return true
   }

谢谢事实上,我只是在发帖后马上就想出来了(已经花了几个小时在这上面了,想想看)。我已经选中了可选链接和链接,但我需要取消选中“可编辑”以使其正常工作。Rashwan,如果我想使文本视图可编辑,但同时也希望在文本视图退出第一响应者时自动检测链接,如在iOS Notes应用程序中?我可以这样做吗?知道在这种情况下什么是链接吗?@GraysonM,根据文档,它是HTTP链接。在textview中,google.in不显示为链接。如果你有什么解决办法,请帮忙
  override func viewDidLoad() {
     super.viewDidLoad()

  let linkAttributes = [
        NSLinkAttributeName: NSURL(string: "http://stalwartitsolution.co.in/luminutri_flow/terms-condition")!
        ] as [String : Any]
  let attributedString = NSMutableAttributedString(string: "Please tick box to confirm you agree to our Terms & Conditions, Privacy Policy, Disclaimer. ")

  attributedString.setAttributes(linkAttributes, range: NSMakeRange(44, 18))

  attributedString.addAttribute(NSUnderlineStyleAttributeName, value: NSNumber(value: 1), range: NSMakeRange(44, 18))

  textview.delegate = self
  textview.attributedText = attributedString
  textview.linkTextAttributes = [NSForegroundColorAttributeName: UIColor.red]
  textview.textColor = UIColor.white
  }


  func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
    return true
   }