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