2017-01-19 119 views
1

我從Xamarin網站這個例子...出於某種原因,這是不工作...添加觸摸的UIView - Xamarin

private UIView buildPage(Page p) { 
    var v = new UIView(); 
    v.UserInteractionEnabled = true; 
    var img = UIImage.FromFile("pages/" +p.filename + ".png"); 
    UIImageView imgView = new UIImageView(new CoreGraphics.CGRect(0, 0, vpWidth, vpHeight)); 
    imgView.Image = img; 
    imgView.ContentMode = UIViewContentMode.ScaleAspectFit; 
    v.Add(imgView); 
    for (int e = 0; e < p.elements.Count; e++) { 
     if (p.elements[e].type == "pageReplace") { 
      UIImageView link = new UIImageView(new CoreGraphics.CGRect(p.elements[e].left, p.elements[e].top, p.elements[e].width, p.elements[e].height)); 
      if (debug) { 
       link.BackgroundColor = UIColor.Green; 
       link.Alpha = 0.5f; 
      } 
      link.UserInteractionEnabled = true; 
      UITapGestureRecognizer tapGesture = new UITapGestureRecognizer(tst); 
      link.AddGestureRecognizer(tapGesture); 
      v.Add(link); 
     } 
    } 
    return v; 
} 
public void tst() { 
    Console.WriteLine("dswwwww"); 
} 

出了什麼問題? 此功能可以把視圖名爲鏈接(綠色),但是當我點擊它..沒有任何反應。

enter image description here

回答

1

我看到一對夫婦的問題:

  1. 您不添加您創建,v第一種觀點,任何上海華盈,所以它不會被屏幕上。
  2. 您還沒有設置第一個視圖的位置/大小v

所以嘗試上述代碼中的一個新的Xam.iOS項目,並添加代碼到ViewControllerViewDidLoad方法固定上述問題,如預期以下工作:

UIView v = new UIView(new CoreGraphics.CGRect(20, 20, View.Frame.Width-40, View.Frame.Height-40)); // Give the first view a position/size 

v.BackgroundColor = UIColor.Gray; // Make it easy to see 

UIView link = new UIView(new CoreGraphics.CGRect(100, 100, 100, 100)); 

//link.UserInteractionEnabled = true; // Not needed. 

link.BackgroundColor = UIColor.Green; // Make it easy to see what to click on 

UITapGestureRecognizer tapGesture = new UITapGestureRecognizer(tst); 

link.AddGestureRecognizer(tapGesture); 

v.Add(link); 

View.Add(v); // View is the main view of the ViewController by default.  

現在點擊按照預期觸發tst()方法。但是沒有必要爲v觀點在這裏,所以下面將正常工作,以及:

UIView link = new UIView(new CoreGraphics.CGRect(100, 100, 100, 100)); 

link.BackgroundColor = UIColor.Green; 

UITapGestureRecognizer tapGesture = new UITapGestureRecognizer(tst); 

link.AddGestureRecognizer(tapGesture); 

View.Add(link); 

你有一個鏈接到該代碼來自文檔?我很好奇看到上下文以及如何避免將v視圖添加到層​​次結構中。另外,因爲我是Xamarin支持工程師,如果文檔中有錯誤,我希望將它們修復。

+0

這是因爲我只是放了一段可能相關的代碼......但我只是編輯它並把所有東西都放在現在。我加入了超級視圖。現在檢查代碼和結果。它基本上是一個返回UIView的函數。 ty! –

+0

Page p = getPage(s); \t \t \t UIView st = buildPage(p); \t \t \t mainContainer.Subviews [curPage] .AddSubview(st); \t \t \t this.View.Add(mainContainer); –

+0

我想你已經擁有了一切:)感謝您的關注。我實際上在學習Xamarin。我來自Appcelerator。 –

0

您是否正在創建一個小部件或Apple Watch擴展? Console.WriteLine()不適用於這些。

+0

這只是一個簡單的iPad應用程序。我曾在很多場合使用過Console.Writeline。 –