2015-11-11 166 views
64

我想使UILabel可點擊。如何使UILabel可點擊?

我已經試過這一點,但它不工作:

class DetailViewController: UIViewController { 

    @IBOutlet weak var tripDetails: UILabel! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     ... 
     let tap = UITapGestureRecognizer(target: self, action: Selector("tapFunction:")) 
     tripDetails.addGestureRecognizer(tap) 
    } 

    func tapFunction(sender:UITapGestureRecognizer) { 
     print("tap working") 
    } 
} 
+3

「UILabel」的框架是什麼?你確定你是在觸摸標籤的框架嗎?你有一個覆蓋標籤的「UIViews」嗎?對於標籤,「userInteractionEnabled」是否設置爲「True」? – JAL

+0

確保您的UILabel IBOutlet與您的筆尖或故事板連接起來 – aahrens

+0

絕佳的作品!謝謝 –

回答

86

你試過設置userInteractionEnabledtruetripDetails標籤上?這應該工作。

+1

感謝您的回答!在這裏,我還有一個關於UITapGestureRecognizer的問題:http://stackoverflow.com/questions/33659078/swift-how-to-make-a-uiview-clickable-in-uitableviewcell –

+0

我想改變水龍頭的背景顏色,但是當我鬆開手指時點擊事件正在觸發。有沒有辦法找到觸碰事件?長按是不是我在找什麼。 –

2

您需要啓用該標籤的用戶交互.....

對於如

yourLabel.userInteractionEnabled = true

+0

這沒有幫助我。我試圖在tableview – Pavlos

9

斯威夫特3更新

yourLabel.isUserInteractionEnabled = true 
+0

的標籤上做到這一點,這並沒有幫助我。我正在嘗試在桌面視圖上的標籤上執行此操作 – Pavlos

+0

可以向我顯示您的代碼以獲取更多詳細信息嗎? –

+0

只是讓它工作歡呼 – Pavlos

53

斯威夫特3更新

替換

Selector("tapFunction:") 

#selector(DetailViewController.tapFunction) 

實施例:

class DetailViewController: UIViewController { 

    @IBOutlet weak var tripDetails: UILabel! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     ... 

     let tap = UITapGestureRecognizer(target: self, action: #selector(DetailViewController.tapFunction)) 
     tripDetails.isUserInteractionEnabled = true 
     tripDetails.addGestureRecognizer(tap) 
    } 

    func tapFunction(sender:UITapGestureRecognizer) { 
     print("tap working") 
    } 
} 
+0

感謝和投票!在swift中工作3 – aznelite89

+0

哇,tnx!利奧爾 –

2

的SWIFT 3.0您也可以改變手勢長按持續時間

label.isUserInteractionEnabled = true 
let longPress:UILongPressGestureRecognizer = UILongPressGestureRecognizer.init(target: self, action: #selector(userDragged(gesture:))) 
longPress.minimumPressDuration = 0.2 
label.addGestureRecognizer(longPress) 
16

SWIFT 4更新

@IBOutlet weak var tripDetails: UILabel! 

override func viewDidLoad() { 
    super.viewDidLoad() 

    let tap = UITapGestureRecognizer(target: self, action: #selector(GameViewController.tapFunction)) 
    tripDetails.isUserInteractionEnabled = true 
    tripDetails.addGestureRecognizer(tap) 
} 

@objc func tapFunction(sender:UITapGestureRecognizer) { 

    print("tap working") 
} 
-1

如在上述溶液中描述 應先使用戶的交互,並添加敲擊手勢

此代碼已使用

Swift4測試 - Xcode 9.2

yourlabel.isUserInteractionEnabled = true 
yourlabel.addGestureRecognizer(UITapGestureRecognizer(){ 
       //TODO 
      })