2017-08-20 68 views
1

老實說,我不知道什麼是錯#selector:我的UIButton不調用該方法針對

func iterate() { 
    scrollView.subviews[0].subviews[0].addSubview(arrowButton) 
    arrowButton.addTarget(self, action: #selector(self.pressButton), for: .touchUpInside) 
    self.view.bringSubview(toFront: arrowButton) 
} 

func pressButton() { 
    print("pouet pouet pouet") 
} 

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

(不介意佈局的事情,我已經刪除了所有的約束清晰度的緣故)

當我按下我的按鈕,什麼都不打印。

我對這個#selector越來越瘋狂了,這麼重要的一塊開發是如何使用這個ObjC垃圾的呢?

編輯:我的UIButton是所有層的頂部,或至少那是什麼的XCode調試工具是說(按鈕在右下角)= enter image description here

+0

我沒有看到任何問題。只用'pressButton'而不用'self.'? – Sweeper

+0

我試過了,我試過了,就像我可以在網上找到的每種語法一樣,但沒有任何工作......每次我必須使用#選擇器,至少半天失去,認真...... – petaire

+0

實際上,問題可能不是成爲選擇者。它可能完全在其他地方。檢查是否調用了「viewDIdLoad」。 – Sweeper

回答

0

我認爲錯誤在這行 (scrollView.subviews [0] .subviews [0] .addSubview(arrowButton之上))

可下,在視圖中添加您的按鈕僅僅指剛檢查

func iterate() { 
    scrollView.subviews[0].subviews[0].addSubview(arrowButton) 
    arrowButton.addTarget(self, action: #selector(self.pressButton), for: .touchUpInside) 
} 

func pressButton() { 
    print("pouet pouet pouet") 
} 

override func viewDidLoad() { 
    super.viewDidLoad() 
    iterate() 
} 
+0

我懷疑過,但我已經添加了self.view.bringSubview(toFront:arrowButton),並且已經使用XCode調試工具進行了檢查(請參閱編輯),它絕對位於頂部... – petaire

+0

您是否添加了箭頭按鈕框架你使用的約束,只是爲UIbutton設置框架 –

+0

我使用約束,但是,然後再次,按鈕位置在Z,Y或X,高度或寬度絕對好,xcode不抱怨任何佈局,在模擬器中一切正常。只是這個M ******** ing#選擇器... – petaire

0

也許這可能是因爲一些問題的Wi語法。試試這個...

arrowButton.addTarget(self, action: #selector(pressButton(_:)), for: .touchUpInside) 

而對於觸摸動作...

func pressButton(_ sender : UIButton){ 

print("Button Tapped") 
} 
+0

嗯它沒有工作,但我很確定這是一個語法問題... – petaire

+0

嗯...嘗試添加此....箭頭按鈕。 addTarget(self,action:#selector(pressButton(sender :)),for:.touchUpInside) –

0

只是爲了調試問題,是不是因爲view hierarchy的,請嘗試更換這行代碼的:

scrollView.subviews[0].subviews[0].addSubview(arrowButton) 

self.view.addSubview(arrowButton) 

2.檢查您arrowButton的下列屬性沒有被設置爲false代碼中的某處:

isEnabled, isUserInteractionEnabled 

這2個屬性必須是true爲了使arrowButton接收touch events

3.檢查您的arrowButton的頂部是否沒有添加任何其他視圖。

4.您提供的selector沒有問題。它工作得很好。我用下面的代碼和它的作品對我來說:

func iterate() 
{ 
    let arrowButton = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) 
    arrowButton.backgroundColor = .red 
    self.view.addSubview(arrowButton) 
    arrowButton.addTarget(self, action: #selector(self.pressButton), for: .touchUpInside) 
    self.view.bringSubview(toFront: arrowButton) 
} 

我覺得view hierarchy以某種方式導致了問題。

相關問題