Display Button With Text & Image In Xamarin IOS

2019-05-21 12:21发布

问题:

I want to design a custom button in Xamarin IOS to display both Text and Image. Please find the below image.

You can find the Text and down arrow symbol in the above image. the down arrow symbol should always display after the text. The button text is dynamic.

Can any one suggest me to solve this.

回答1:

You want to use the TitleEdgeInsets & ImageEdgeInsets properties of the UIButton to control where the inset of the text and image begins:

button.TitleEdgeInsets = new UIEdgeInsets(0, -button.ImageView.Frame.Size.Width, 0, button.ImageView.Frame.Size.Width);
button.ImageEdgeInsets = new UIEdgeInsets(0, button.TitleLabel.Frame.Size.Width, 0, -button.TitleLabel.Frame.Size.Width);

Full Example:


    button = new UIButton(UIButtonType.System);
    button.Frame = new CGRect(150, 20, 200, 50);
    button.Layer.CornerRadius = 5;
    button.BackgroundColor = UIColor.Black;
    button.SetTitleColor(UIColor.White, UIControlState.Normal);
    button.SetImage(UIImage.FromFile("ratingstar.png"), UIControlState.Normal);
    button.SetTitle("StackOverflow", UIControlState.Normal);
    button.TitleEdgeInsets = new UIEdgeInsets(0, -button.ImageView.Frame.Size.Width, 0, button.ImageView.Frame.Size.Width);
    button.ImageEdgeInsets = new UIEdgeInsets(0, button.TitleLabel.Frame.Size.Width, 0, -button.TitleLabel.Frame.Size.Width);