2013-04-29 67 views
0

我知道有幾個關於圖像和文本在按鈕中的位置的問題,但我仍然無法完成它的工作。我希望標題顯示在圖像下方。如果沒有圖像,則標題顯示我期望的位置。但是,如果有圖像,標題不會顯示。帶圖像和文本的UIButton

代碼粘貼在下面。明天我可以嘗試子類化UIButton並調整子視圖,但是這個應該工作。我認爲。你能明白爲什麼它不會?

在此先感謝!

private static float h = 200.0f; 
private static float w = 200.0f; 
private static float padding = 10.0f; 
private static float textheight = 20f; 

for (int i=0; i<numPlants; i++) 
{ 
    var button = UIButton.FromType (UIButtonType.RoundedRect); 
    button.Frame = new RectangleF (padding * (i + 1) + (i * w), 
            padding, w, (h + textheight + 2)); 
    UIImage img = _group.Plants[i].GetImage(); 
    if (img != null) 
    { 
     button.SetImage(img, UIControlState.Normal); 
     button.ImageEdgeInsets = new UIEdgeInsets(0.0f, 0.0f, (textheight + 20), 0.0f); 
    } 

    button.TitleEdgeInsets = new UIEdgeInsets((h+2), 0.0f, 0.0f, 0.0f); 
    button.SetTitleColor(UIColor.Black, UIControlState.Normal);    
    button.SetTitle(_group.Plants[i].Pltnme, UIControlState.Normal); 

    plantScrollView.AddSubview (button); 

    Plant plt = _group.Plants[i]; 
    button.TouchUpInside += (sender, e) => { 
     _navController.PushViewController(new SecondViewController(plt), true); 
    }; 
} 

回答

0

您是否嘗試過使用XIB或Storyboard,然後添加UIImageView和Label來創建您所期望的?我覺得這比編碼簡單很多。

+0

感謝您的想法!我也可以做到這一點。我仍在使用獨立版本,所以我試圖儘可能保持代碼儘可能小。該方法的另一個問題是,我仍然需要按鈕功能,所以我需要在上面放一個透明按鈕。在閱讀其他人如何實現這種功能時,這種方法看起來好像是最簡單的。 – 2013-05-02 19:58:26