for my iOS app (swift) I'm trying to add a custom UIView above the tableView. When the user pulls down the tableView, the app should look as in this screenshot.
The text in the blue area at the top ("Zorneding ...") is still part of the tableView header. The blue area above the text is a UIView, which I've added in the ViewDidAppear
function of the TableViewController.
The code I'm using for adding the UIView in ViewDidAppear
is as follows.
// Blue background view behind refresh control
var frame = tableView.bounds
frame.origin.y = -frame.size.height
frame.size.width -= 10
frame.origin.x += 5
let refreshBackgroundView = UIView(frame: frame)
refreshBackgroundView.backgroundColor = GlobalConstants.Color.ZeroBlue
tableView.insertSubview(refreshBackgroundView, atIndex: 0)
This code works perfectly well in portrait orientation. But when rotating the device to landscape, the refreshBackgroundView
of course does not change it's size and therefore only covers parts of the screen.
I've already tried to add constrains to the refreshBackgroundView
, but I can't get them working.
The other thing I've tried is to subclass the UIRefreshControl
and to configure its background there, but when pulling down the tableView, a small gap between the tableView header and the refresh control view is visible (the tableView background shines through).
Any idea of how to make my code work when the device is rotated?
Thanks!
Solution:
The solution was easy enough. Using layout constraints. I don't know why those didn't work for me yesterday.
Here's the new code:
// Add background view behind UIRefreshControl
let refreshBackgroundView = UIView()
refreshBackgroundView.backgroundColor = GlobalConstants.Color.ZeroBlue
tableView.insertSubview(refreshBackgroundView, atIndex: 0)
refreshBackgroundView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint(item: refreshBackgroundView, attribute: .Height, relatedBy: .Equal, toItem: tableView, attribute: .Height, multiplier: 1.0, constant: 0.0).active = true
NSLayoutConstraint(item: refreshBackgroundView, attribute: .Width, relatedBy: .Equal, toItem: tableView, attribute: .Width, multiplier: 1.0, constant: -10.0).active = true
NSLayoutConstraint(item: refreshBackgroundView, attribute: .Bottom, relatedBy: .Equal, toItem: tableView, attribute: .Top, multiplier: 1.0, constant: 0.0).active = true
NSLayoutConstraint(item: refreshBackgroundView, attribute: .CenterX , relatedBy: .Equal, toItem: tableView, attribute: .CenterX, multiplier: 1.0, constant: 0.0).active = true