mirror of
https://github.com/material-components/material-components-ios.git
synced 2026-02-20 08:27:32 +08:00
1.5 KiB
1.5 KiB
Background images
This example shows how to add a custom background image view to a flexible header.
You can create and add a UIImageView subview to the flexible header view's content view:
Swift
let headerView = headerViewController.headerView
let imageView = ...
imageView.frame = headerView.bounds
imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
headerView.contentView.insertSubview(imageView, at: 0)
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
Objective-C
UIImageView *imageView = ...;
imageView.frame = self.headerViewController.headerView.bounds;
imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self.headerViewController.headerView.contentView insertSubview:imageView atIndex:0];
imageView.contentMode = UIViewContentModeScaleAspectFill;
imageView.clipsToBounds = YES;
Notes:
- Add the image view to the header view's
contentView, not the header view itself. - Set the
contentModeto "ScaleAspectFill" to ensure that the image always fills the available header space, even if the image is too small. This is usually preferred, but consider changing the contentMode if you want a different behavior. - Enable
clipsToBoundsin order to ensure that your image view does not bleed past the bounds of the header view. The header view'sclipsToBoundsis disabled by default.