8
votes

Context:

I'm trying to make an app consisting of a grid of buttons. Some of them have a text larger than it's own width

Problem:

The thing is that XF Button is "wrapping" the text replacing some characters in the middle with ellipsis (...):

[Button text]1]

I would like the text to be wrapped in multiple lines like the text in Labels:

enter image description here

Surfing the internet I found some approaches:

  • Using a Button and a Label inside a RelativeLayout. The Label overlaps the Button and setting the InputTransparent property to true you can achieve the Button-like control.

  • Using a Label inside a Layout and handling the Tap Gestures

  • Using platform-specific code to render the native buttons with a CustomRenderer (I would prefer not to have platform-specific code to show buttons)

The problem with those approaches is that the result doesn't look like a native button or doesn't behave like a native button.

There is an approach that can give both things? A control that looks and behaves like a native button.

1

1 Answers

17
votes

Using platform-specific code to render the native buttons with a CustomRenderer (I would prefer not to have platform-specific code for showing the buttons)

This is the best solution IMO. It will give you the look and feel of a native button.

Since a Forms button does not expose a word wrap property, then you have to use the properties of the native control to do this. Here is the very simple code for a custom renderer on iOS to enable word wrapping:

using System;
using NameSpaceForMyiOSApp;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(Button), typeof(MyButtonRenderer))]
namespace NameSpaceForMyiOSApp
{
    public class MyButtonRenderer : ButtonRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
        {
            base.OnElementChanged(e);
            if (Control != null)
                Control.TitleLabel.LineBreakMode = UIKit.UILineBreakMode.WordWrap;
        }
    }
}

On Android, the text does wrap by default, so no custom renderer needed, but note that if a single word is to long to fit in the button's width the word itself will be split. The only solution I can think of here is to make sure your button width is wide enough to hold the longest word in the button text. See this SO answer for more info on this: Wrap text in button gracefully at whitespace