Some test text!

Search
Hamburger Icon

Xamarin / Guides

Adding a view to a page

You can add a custom View or UIView object to a page.

Add a custom view to a page in Xamarin.iOS

This tutorial only applies to Xamarin.iOS. See Xamarin.Android equivalent here .

This guide demonstrates how to make a UIView appear as if it is stuck to a page.

It is convenient for the user to make a UIView that is "stuck" to a page record its desired page location. To do this, you could add an extension/category to a UIView, or use a derived class, as shown below:

public class FloatingView : UIView
{
    public FloatingView() : base()
    {

    }

    public int PageNumber { get; set; }

    public pdftron.PDF.Rect PdfPageRect { get; set; }
}

In this example, we will add a red square to a location near the bottom left hand corner of the first page:

var mCustomView = new FloatingView();
mCustomView.BackgroundColor = UIColor.Red;
mCustomView.PageNumber = 1;
mCustomView.PdfPageRect = new Rect(10, 10, 100, 100);
mPdfViewCtrl.OverlayView.AddSubview(mCustomView);

// position the view
positionFloatingViews();

Without the last line in the code snippet above, the new view would not appear in the correct location. The following method will position it, and any others that have been added:

void positionFloatingViews()
{
    foreach (UIView view in mPdfViewCtrl.OverlayView.Subviews)
    {
        if (view is FloatingView)
        {
            var overlayView = view as FloatingView;
            bool pageHidden = false;
            if (!mPdfViewCtrl.PagePresentationModeIsContinuous)
            {
                pageHidden = !mPdfViewCtrl.PageIsOnScreen(overlayView.PageNumber);
            }
            overlayView.Hidden = pageHidden;
            CGRect screenRect = mPdfViewCtrl.PDFRectPage2CGRectScreen(TypeConvertHelper.ConvRectToNative(overlayView.PdfPageRect), overlayView.PageNumber);
            screenRect.X += (nfloat)mPdfViewCtrl.GetHScrollPos();
            screenRect.Y += (nfloat)mPdfViewCtrl.GetVScrollPos();
            overlayView.Frame = screenRect;
        }
    }
}
Floating UIView
A red `UIView` positioned near the bottom left hand corner of the first page.

Whenever the PDF page shifts within the PTPDFViewCtrl, which may happen when changing the page presentation mode, zooming, and such, the views need to be re-positioned (positionFloatingViews needs to run again). To do this, implement the PTPDFViewCtrl delegate methods pdfScrollViewDidEndZooming: and onLayoutChanged, and in them, call positionFloatingViews:

mPdfViewCtrl.PdfViewCtrlOnLayoutChanged += (sender, e) =>
{
    positionFloatingViews();
};
mPdfViewCtrl.PdfScrollViewDidEndZooming += (sender, e) =>
{
    positionFloatingViews();
};

Get the answers you need: Chat with us