2012-04-11 88 views
-1

在我的項目中,我設置了一個視圖作爲我的應用程序的根視圖。無法專注於文本字段

在該根視圖的控制器,我已得到這樣的層次結構:

rootview - [addsubview] - foregroundView - [addsubview] - 文本字段

I」我已經做了代碼而不是xib。

在這種情況下,文本字段無法集中。當我點擊屏幕上的文本框時,似乎沒有任何事情發生。但是,如果我修改這樣的:

rootview - [addsubview] - foregroundView

rootview - [addsubview] - 文本框

,一切運行良好。

因爲我想讓foregroundView和textfield成爲一個組,所以我更喜歡使用前一種風格。有沒有想法呢?非常感謝。

這裏是我的麻煩的核心源代碼:

//it's a viewController.m , it's view has been set as the root view for the app. 
self.foregroundView = [[UIImageView alloc] initWithFrame:CGRectMake(15, 140, 290, 250)]; 
UIImage *foregroundImage = [XYZImageProcessor resizeImage:[UIImage imageNamed:@"Texture0203.jpg"] toSize:CGSizeMake(275, 250)]; 
[self.view addSubview:self.foregroundView ]; 
self.nickNameTextField = [self.class customTextFieldMake:CGRectMake(80, 200, 150, 30)]; 
[self.view addSubview:self.nickNameTextField]; 
//if I change it to [self.foregroundView addSubview:self.nickNameTextField],the textfield can not be focused. 
+0

你是什麼意思'不會關注'?鍵盤是否出現? – CodaFi 2012-04-11 03:32:58

+0

您可以在構建視圖層次結構的位置發佈代碼嗎? – danh 2012-04-11 04:51:36

+0

'不會聚焦'意味着當我觸摸屏幕上的文本框時,鍵盤不會出現。我現在將添加一些源代碼,對此感到抱歉 – biaobiaoqi 2012-04-11 04:56:24

回答

2

聽起來好像你的foregroundView已將userInteractionEnabled設置爲NO。這並不意味着foregroundView不會收到觸摸事件 - 它的任何子視圖都不會。見How to get touches when parent view has userInteractionEnabled set to NO in iOS。 (簡答:不行)

因此,在建立您的意見時,請嘗試設置[foregroundView setUserInteractionEnabled:YES]

如果foregroundView實現它自己的hitTest:withEvent:它也可以防止與其子視圖的交互。

+0

非常感謝。它運作良好! – biaobiaoqi 2012-04-11 05:35:16

0

嘗試在viewWillAppear中這樣做:

[desiredField becomeFirstResponder]; 

通過使該領域的第一個響應者,它具有焦點和鍵盤將被顯示。

+0

調用-becomeFirstResponder並不是一個好主意。該方法的文檔具體聲明「使用NSWindow makeFirstResponder:方法,而不是此方法,使對象成爲第一響應者,不要直接調用此方法。」 https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSResponder_Class/Reference/Reference.html#//apple_ref/occ/cl/NSResponder – Vervious 2012-04-11 03:59:45

+0

謝謝:)。成爲FirstResponder將獲得鍵盤,但它出現在一開始,沒有我的控制。退出鍵盤後,我仍然無法專注於此。 makeFirstResponder應該在NSWindow中調用,這可能不適合我的情況。 – biaobiaoqi 2012-04-11 04:35:45