It feels like this should be fairly simple but nothing i've tried so far has worked. In a nutshell, I want to add a fixed image just below the navigation bar in a UITableViewController that i create programmatically. In other words, I want the image to stay just below the navigation bar even as the user scrolls up and down the table view (it's basically a custom drop-shadow for the navigation bar).
The closest I've gotten is the code below (in the UITableViewController's init method), which adds the image but doesn't keep it from moving when the user scrolls.
// Add nav bar drop shadow
UIImage *dropShadowImage = [UIImage imageNamed:@"NavBarDropShadow.png"];
UIImageView *dropShadowView = [[UIImageView alloc] initWithImage:dropShadowImage];
[self.view addSubview:dropShadowView];
Is there an easy way to add an add an image to the screen programmatically, position it wherever you like, and have it stay there even as the user scrolls? Thanks for any and all input!
You can make a subclass or a category on UINavigationBar, and have it add the image in the
init
ordrawRect
methods. If you think about it, you're trying to add a shadow to the navigation bar, not to the UITableView, so it makes sense to modify the navbar, not the table.EDIT: IOS5 has a better way to do this. Please check out the new UIAppearance protocol.
Adding this block of code to your code will allow you to draw your shadow on all UINavigationBars in the app. This is a better solution than adding the shadow as a UIImageView:
To make the UINavigationBar higher and thus not clipping your content, override the
layoutSubviews
and set the frame you need (the code above assumes your header is 300 points high).layoutSubviews
does nothing by default, but is "lazy" called before lay-outing the view.For more info about this custom size/look overrides that apply to UIView (and any other subclass) have a look here
You are adding your dropShadowView to self.view that in your case is the view of an UITableViewController. It means that your self.view is an UITableView so when you scroll up and down you scroll the dropShadowView as well because is inside the tableView.
Try to write a custom UIViewController and add two subviews: one is the dropShadowView and the other one is your table.
Dont make a
UITableView
the main view ie. theview
outlet, set that to aUIView
that contains aUITableView
, then make your controller a subclass ofUIViewController
, and make it conform toUITableViewDataSource
andUITableViewDelegate
. in your nib, set up your view so that you have a UIImageView at the top and a UITableView below. and set thedelegate
anddatasource
to yourfile's owner
.Have a look at this similar question I answered a while back. It should do exactly what you want with little customization.
Transparent View at the Top of a UITableView