签入单元格(在 TextView 中)文本或 link (Swift)

Check in cell (in TextView) text or link (Swift)

我有一个 table 带有 ImageViewTextView

我如何检查单元格中是否有 text 然后(在图像视图中 = 图像 "Text"),否则如果单元格中有 link(在图像视图中 = 图像 "Link")

var myData: [String] = []

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
    if (URL.scheme?.contains("http"))! || (URL.scheme?.contains("https"))! {
        cell.ImageV?.image = UIImage(named:"Link")
        print("Link")
    } else {
        cell.ImageV?.image = UIImage(named:"Text")
        print("Text")
    }
    return false
}

示例:

但是不行

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell
    cell.nameText?.text = myData[indexPath.row]
    //
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        if (URL.scheme?.contains("http"))! || (URL.scheme?.contains("https"))! {
            // Handle links
            cell.ImageV?.image = UIImage(named:"Link")
            print("Link")
        } else {
            // Handle anything else that has slipped through.
            cell.ImageV?.image = UIImage(named:"Text")
            print("Text")
        }
        return false
    }
    return cell
}

保存和加载:

func save() {
  UserDefaults.standard.set(myData, forKey: "notes")
  //UserDefaults.standard.set(Data, forKey: "ImageDate")
  UserDefaults.standard.synchronize()
}
//
func load(){
    if let loadData = UserDefaults.standard.stringArray(forKey: "notes") {
        myData = loadData

        table.reloadData()
    }
}

已更新

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell     
{
     let dict = myData[indexPath.row]

     if dict.contains("http") || dict.contains("https")
     {
          print("Link")
     }
     else{
          print("Text")
     }
}

希望对您有所帮助

您可以使用以下代码检查文本是否 URL

guard let url = URL(string: self.text!) else { return false }
if UIApplication.shared.canOpenURL(url) {
    // url
}else {
    //not an url
}