UITextView vertical alignment in a custom renderer not initializing properly

DavidPerssonDavidPersson USMember ✭✭

I've written a custom renderer for an Editor view and want to set the vertical alignment.

Because there is no VerticalAlignment on the native Control for the Editor, I've set up my own logic to add an offset to the content. (based on this stack exchange post)

This offset is supposed to be set when the 'Text' property of my element changes, which I check for in the OnPropertyChanged method.

The problem is, when the TextView is first loaded on screen, the content is aligned near the top.

When I change the text the alignment is adjusted properly.

To determine the content offset, I'm trying to access the Content.Bounds.Height property. However this is set to 0 before the view is rendered on screen.

Is there an easier way to vertically align text in a UITextView for iOS?

Here is my renderer:

[assembly: ExportRenderer(typeof(xInputString), typeof(xInputStringRenderer))] namespace TabletVTTest.iOS { public class xInputStringRenderer : EditorRenderer { xInputString view;

    protected override void OnElementChanged(ElementChangedEventArgs<Editor> e)
    {
        base.OnElementChanged(e);
        view = (xInputString)this.Element;

        setVerticalAlign();

    }

    protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);

        Debug.WriteLine("Changed: " + e.PropertyName);

        if(e.PropertyName == "Text"){
            setVerticalAlign();
        } 
    }

    void setVerticalAlign()
    {

        // !!  Control.Bounds.Height is set to 0 initially.. How do I change this? 

        float topCorrect = (float)(Control.Bounds.Height - Control.ContentSize.Height);

        topCorrect = topCorrect / 2;
        //topCorrect = topCorrect < 0.0 ? (float) 0.0 : topCorrect;

        if (Control.ContentSize.Height < Control.Bounds.Height) 
        {
            Control.SetContentOffset(new CGPoint(0, -topCorrect),true);
        }
    }

}

}

Sign In or Register to comment.