UIButton with an image and text

I know there are several questions regarding the placement of images and text in buttons, but I still can't quite get it to work. I want the title to display below the image. If there is no image, the title displays where I would expect. However, if there is an image, the title does not display.

The code is pasted below. Tomorrow I can try subclassing UIButton and tweaking the subviews, but this should work. I think. Can you see why it wouldn't?

Thanks in advance!

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);
    };
}

Have you tried using XIB or Storyboard and then adding a UIImageView and Label to create what you are desiring? I feel that this would be a lot simpler than coding it.

链接地址: http://www.djcxy.com/p/28250.html

上一篇: 如何在使用auto时更改默认的UIButton填充

下一篇: 带图像和文字的UIButton