2011-11-04 89 views
1

我嘗試使用工具欄的自定義視圖創建UIBarButtonItem。視圖本身很好地顯示,但是當我單擊BarButton時,不會發生任何操作。它看起來像觸摸事件不會從視圖轉發到UIBarButtonItem實例。我檢查了響應鏈,我認爲它看起來不錯。我也搜索了互聯網並檢查了Apple的文檔,但找不到任何提示。具有自定義視圖的UIBarButtonItem

這裏是我的代碼:

g__objWeatherButton = new UIBarButtonItem[1]; 

    UIView l__objCustomView = g__objWeatherDisplay.InfoBarButton; // Returns a reference to my custom view 

    UIBarButtonItem l__objButton = new UIBarButtonItem(l__objCustomView); 

    l__objButton.Clicked += delegate {this.WeatherButtonEvent();}; // my action handler 
    l__objButton.Width = 200; 
    l__objButton.Enabled = true; 

    g__objWeatherButton[0] = l__objButton; 

    this.Items = g__objWeatherButton; // "this" is my UIToolbar object 

有人可以給我一個提示,問題出在哪裏?或者一個工作代碼示例(請在c#中 - 在Objective-C中找到了一些示例,但顯然忽略了關鍵技巧;-)

回答

5

沒有什麼特別的技巧。當您想要將自定義視圖添加到工具欄或導航欄時,您應該訂閱(並響應)該視圖的事件。因此,不是使用UIView來保存圖像,而是使用UIButtonType.Custom創建一個UIButton,並訂閱該按鈕的TouchUpInside事件。

您對其進行初始化像你UIView的事:

UIButton l__objCustomUIButton = UIButton.FromType(UIButtonType.Custom); 
//l__objCustomUIButton.SetImage(UIImage.FromFile("your button image"), UIControlState.Normal); 
l__objCustomUIButton.TouchUpInside += delegate { this.WeatherButtonEvent(); }; 
UIBarButtonItem l__objButton = new UIBarButtonItem(l__objCustomUIButton); 

只要確保你在聲明類範圍的按鈕。

+0

海蘭季米特里斯 我有這個想法太多,但我拒絕了,因爲我以爲會有一個更簡單的方法。現在我已經在這種方式實現它,它工作正常。謝謝你的幫助! –

+0

不客氣,很高興我幫了忙。 –

+1

@Jörn請將答案標記爲已接受,以便每個在stackoverflow上搜索或閱讀的人都會立即知道答案可用於問題。謝謝! – poupou

3

儘管答案讓我朝着正確的方向,但仍然無法顯示按鈕。只有在我添加了下面的按鈕後才顯示圖像。

l__objCustomUIButton.Frame = new System.Drawing.RectangleF(0,0,40,40);

問候 保羅

0

還有一個更簡單的方法和自定義按鈕現在像一個普通的工具欄按鈕反應。

this.SetToolbarItems(new UIBarButtonItem[] { 
      new UIBarButtonItem(UIBarButtonSystemItem.Refresh, (s,e) =>  { 
       Console.WriteLine("Refresh clicked"); 
      }) 

      , new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace) { Width = 50 } 
      , new UIBarButtonItem(UIImage.FromBundle 
            ("wrench_support_white.png"), UIBarButtonItemStyle.Plain, (sender,args) => { 
       Console.WriteLine("Support clicked"); 
      }) 
     }, false); 
相關問題