2016-12-02 33 views
2

我有一個自定義單元格,它具有名爲StatusText的UITextView。我有一個擴展名,它可以在textView中找到所有@符號並將其變爲鏈接。我希望能夠點擊該用戶名鏈接並轉到配置文件視圖控制器。自定義單元格中的鏈接UITextView註冊分接頭

這裏是CustomCell的下面的代碼:

import UIKit 

class profileCell: UITableViewCell, UITextViewDelegate { 
    @IBOutlet weak var UserImage: UIImageView! 
    @IBOutlet weak var UserName: UILabel! 
    @IBOutlet weak var Time: UILabel! 
    @IBOutlet weak var Likes: UILabel! 

    @IBOutlet weak var Dislikes: UILabel! 

    @IBOutlet weak var StatusText: UITextView! 

    @IBOutlet weak var LikeButton: UIButton! 

    @IBOutlet weak var DislikeButton: UIButton! 

     override func awakeFromNib() { 
      StatusText.delegate = self 
     } 

func StatusText(StatusText: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool { 
    /* perform your own custom actions here */ 
    print("firing this right now") 

    return true // return true if you still want UIAlertController to pop up 
    } 
} 

回答

0

這聽起來像你想執行SEGUE到另一個視圖控制器,並通過二者之間的用戶名。請查看Apple's documentation以獲取有關如何在兩個視圖控制器之間創建輪廓的信息,有關如何將數據從一個視圖控制器傳遞到下一個視圖控制器的信息,請參閱此StackOverflow answer。另外,在委託中創建方法時,您需要將方法名稱與協議中的完全一致,因爲iOS不知道調用您的自定義命名方法。如果從最後一個環節按照選項#2,您的最終功能會是這個樣子(編輯:現在固定的工作答案已發現):

func textView(_ textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool { 
    guard let username = self.getUsernameFrom(URL) else { return false } // I'll let you implement this as an exercise. :) 

    let profileVC = ProfileViewController() 
    profileVC.username = username 

    profileVC.performSegueWithIdentifier("profileSegue", sender: self) 

    return true 
} 
+0

這是完美的,問題是,當鏈接被點擊時,函數不會觸發。我試着把這個函數放在customCell.swift類中,但是當鏈接被點擊時什麼也沒有發生。它被設置爲被選中。我認爲該功能無法找到單元格內的鏈接。 –

+0

@MatthewFoster,你可以驗證'awakeFromNib'被調用,並且'StatusText'在這個時候被實例化嗎? –

+0

所以awakeFromNib在tableView第一次加載視圖控制器時被調用。在customCell單元格可見時,向上和向下滾動表格,awakeFromNib不會觸發。 –

0

所以不是使委託customCell我把viewController作爲委託並且做了@kgaleman所說的如下,並且被解僱了。

func textView(_ textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool { 
    /* perform your own custom actions here */ 

    print(URL) 

    return true // return true if you still want UIAlertController to pop up 

} 
+0

很高興工作!我用適當的方法標題更新了我的答案,並解釋了爲什麼它能起作用,所以未來的初學者可能會理解這個問題,以及它爲什麼會起作用。乾杯! –