Оформление рекламных макетов с помощью нативных шаблонов.

Select platform: Android iOS Flutter

Download Native Templates

Использование нативной рекламы позволяет персонализировать объявления, что приводит к улучшению пользовательского опыта. Улучшенный пользовательский опыт может повысить вовлеченность и увеличить общую прибыль.

Чтобы максимально эффективно использовать нативную рекламу, важно оформить макеты объявлений так, чтобы они органично вписывались в ваше приложение. Для начала мы создали нативные шаблоны.

Native Templates are code-complete views for your native ads, designed for fast implementation and easy modification. With Native Templates, you can implement your first native ad in just a few minutes, and you can quickly customize the look and feel without a lot of code. You can place these templates anywhere you want, such as in a TableView used in a news feed, in a dialog, or anywhere else in your app.

В этом руководстве показано, как загрузить, включить и использовать нативные шаблоны в ваших iOS-приложениях. Предполагается, что вы уже успешно использовали SDK для загрузки нативной рекламы.

Template sizes

There are two template sizes: small and medium. Each template is represented by a class. The classes are GADTSmallTemplateView and GADTMediumTemplateView . Both classes extend GADTTemplateView . Both templates have a fixed aspect ratio, which will scale to fill the width of their parent views only if you call addHorizontalConstraintsToSuperviewWidth . If you don't call addHorizontalConstraintsToSuperviewWidth , each template will render its default size.

GADTSmallTemplateView

The small template is ideal for UICollectionView or UITableView cells. For instance you could use it for in-feed ads, or anywhere you need a thin rectangular ad view. The default size of this template is 91 points high by 355 points wide.

GADTMediumTemplateView

Средний шаблон предназначен для отображения от половины до трех четвертей страницы. Он хорошо подходит для целевых страниц или заставок, но также может быть включен в UITableViews . Размер шаблона по умолчанию составляет 370 пунктов в высоту и 355 пунктов в ширину.

Все наши шаблоны поддерживают автоматическую компоновку, поэтому смело экспериментируйте с размещением элементов. Конечно, вы также можете изменить исходный код и файлы xib в соответствии со своими требованиями.

Installing the native ad templates

To install the Native Templates, simply download the zip and drag it into your Xcode project. Make sure you check Copy items if needed .

Using the native ad templates

После добавления папки в проект и включения соответствующего класса в файл, следуйте этому руководству, чтобы использовать шаблон. Обратите внимание, что изменить свойства шрифта и стиля можно только с помощью словаря стилей — в настоящее время мы переопределяем любые стили, заданные в самом файле xib.

Objective-C

/// Step 1: Import the templates that you need.
#import "NativeTemplates/GADTSmallTemplateView.h"
#import "NativeTemplates/GADTTemplateView.h"
...

// STEP 2: Initialize your template view object.
GADTSmallTemplateView *templateView =
    [[NSBundle mainBundle] loadNibNamed:@"GADTSmallTemplateView" owner:nil options:nil]
      .firstObject;

// STEP 3: Template views are just GADNativeAdViews.
_nativeAdView = templateView;
nativeAd.delegate = self;

// STEP 4: Add your template as a subview of whichever view you'd like.
// This must be done before calling addHorizontalConstraintsToSuperviewWidth.
// Please note: Our template objects are subclasses of GADNativeAdView so
// you can insert them into whatever type of view youd like, and dont need to
// create your own.
[self.view addSubview:templateView];

// STEP 5 (Optional): Create your styles dictionary. Set your styles dictionary
// on the template property. A default dictionary is created for you if you do
// not set this. Note - templates do not currently respect style changes in the
// xib.

NSString *myBlueColor = @"#5C84F0";
NSDictionary *styles = @{
    GADTNativeTemplateStyleKeyCallToActionFont : [UIFont systemFontOfSize:15.0],
    GADTNativeTemplateStyleKeyCallToActionFontColor : UIColor.whiteColor,
    GADTNativeTemplateStyleKeyCallToActionBackgroundColor :
        [GADTTemplateView colorFromHexString:myBlueColor],
    GADTNativeTemplateStyleKeySecondaryFont : [UIFont systemFontOfSize:15.0],
    GADTNativeTemplateStyleKeySecondaryFontColor : UIColor.grayColor,
    GADTNativeTemplateStyleKeySecondaryBackgroundColor : UIColor.whiteColor,
    GADTNativeTemplateStyleKeyPrimaryFont : [UIFont systemFontOfSize:15.0],
    GADTNativeTemplateStyleKeyPrimaryFontColor : UIColor.blackColor,
    GADTNativeTemplateStyleKeyPrimaryBackgroundColor : UIColor.whiteColor,
    GADTNativeTemplateStyleKeyTertiaryFont : [UIFont systemFontOfSize:15.0],
    GADTNativeTemplateStyleKeyTertiaryFontColor : UIColor.grayColor,
    GADTNativeTemplateStyleKeyTertiaryBackgroundColor : UIColor.whiteColor,
    GADTNativeTemplateStyleKeyMainBackgroundColor : UIColor.whiteColor,
    GADTNativeTemplateStyleKeyCornerRadius : [NSNumber numberWithFloat:7.0],
};

templateView.styles = styles;

// STEP 6: Set the ad for your template to render.
templateView.nativeAd = nativeAd;

// STEP 7 (Optional): If you'd like your template view to span the width of your
// superview call this method.
[templateView addHorizontalConstraintsToSuperviewWidth];
[templateView addVerticalCenterConstraintToSuperview];

Style dictionary keys

Самый быстрый способ настроить шаблоны — создать словарь со следующими ключами:

Objective-C

/// Call to action font. Expects a UIFont.
GADTNativeTemplateStyleKeyCallToActionFont

/// Call to action font color. Expects a UIColor.
GADTNativeTemplateStyleKeyCallToActionFontColor;

/// Call to action background color. Expects a UIColor.
GADTNativeTemplateStyleKeyCallToActionBackgroundColor;

/// The font, font color and background color for the first row of text in the
/// template.

/// All templates have a primary text area which is populated by the native ad's
/// headline.

/// Primary text font. Expects a UIFont.
GADTNativeTemplateStyleKeyPrimaryFont;

/// Primary text font color. Expects a UIFont.
GADTNativeTemplateStyleKeyPrimaryFontColor;

/// Primary text background color. Expects a UIColor.
GADTNativeTemplateStyleKeyPrimaryBackgroundColor;

/// The font, font color and background color for the second row of text in the
/// template.

/// All templates have a secondary text area which is populated either by the
/// body of the ad, or by the rating of the app.

/// Secondary text font. Expects a UIFont.
GADTNativeTemplateStyleKeySecondaryFont;

/// Secondary text font color. Expects a UIColor.
GADTNativeTemplateStyleKeySecondaryFontColor;

/// Secondary text background color. Expects a UIColor.
GADTNativeTemplateStyleKeySecondaryBackgroundColor;

/// The font, font color and background color for the third row of text in the
/// template. The third row is used to display store name or the default
/// tertiary text.

/// Tertiary text font. Expects a UIFont.
GADTNativeTemplateStyleKeyTertiaryFont;

/// Tertiary text font color. Expects a UIColor.
GADTNativeTemplateStyleKeyTertiaryFontColor;

/// Tertiary text background color. Expects a UIColor.
GADTNativeTemplateStyleKeyTertiaryBackgroundColor;

/// The background color for the bulk of the ad. Expects a UIColor.
GADTNativeTemplateStyleKeyMainBackgroundColor;

/// The corner rounding radius for the icon view and call to action. Expects an
/// NSNumber.
GADTNativeTemplateStyleKeyCornerRadius;

Часто задаваемые вопросы

Почему при попытке создать экземпляр шаблонного объекта возникает исключение?
Это может произойти, если вы изменили размер представления в файле xib, но не изменили размер фрейма, созданного в методе "setup" подкласса.
How can I further customize these templates?
Эти шаблоны представляют собой просто файлы xib с соответствующими объектами представления, как и любые другие файлы xib и пользовательские классы представления, к которым вы, возможно, привыкли в разработке под iOS. Если вы предпочитаете создавать нативную рекламу с нуля, ознакомьтесь с нашим руководством по расширенным нативным решениям .
Почему мои стили не обновляются, когда я устанавливаю их в файле xib?
В настоящее время мы переопределяем все стили xib-файлов с помощью словаря стилей по умолчанию в GADTTemplateView.m .

Способствовать

We've made Native Templates to help you develop native ads quickly. We'd love to see you contribute to our GitHub repo to add new templates or features. Send us a pull request and we'll take a look.