Update tableView's headerView on device rotation - ios

I have table view with a custom header view. In the header view I have a subview that is a UIImage. On rotation, the header view and it's subviews don't update to where they should be. Instead, they retain their positions until the user either presses a button, moves to a different page, etc. Essentially, their positions don't update until the user interacts with the app in some way.
I am detecting device rotation with:
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
// Update header views!
}
I can't find any sort of code that will update the header view and it's subviews though. Any help appreciated.
EDIT: Here is the code for my header view:
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, tableView.sectionHeaderHeight))
let headerColor = UIColor.blueColor()
headerView.backgroundColor = headerColor
headerView.tag = section
let headerString = UILabel(frame: CGRect(x: 10, y: 10, width: tableView.frame.size.width-45, height: 30)) as UILabel
headerString.text = "Title"
headerString.textColor = UIColor.whiteColor()
headerView.addSubview(headerString)
let headerTapped = UITapGestureRecognizer(target: self, action:"sectionHeaderTapped:")
headerView.addGestureRecognizer(headerTapped)
// Button in header
let gearImage = UIImage(named: "icons_button")
let width = CGFloat(45)
let rightInset = CGFloat(10)
let headerButton = UIButton(frame: CGRect(x: headerView.frame.maxX - 45, y: 7, width: width, height: width - rightInset))
headerButton.setImage(gearImage, forState: UIControlState.Normal)
headerButton.tag = section
headerButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: rightInset)
headerButton.addTarget(self, action: "userButtonPress:", forControlEvents: UIControlEvents.TouchUpInside)
headerView.addSubview(headerButton)
return headerView
}

in viewForHeaderInSection add a container like UIVIEW
and then in container add childview like label then
add this line
label.autoresizingMask = .flexibleWidth

Although it seems like overkill, this works well:
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
[coordinator animateAlongsideTransition: ^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) {
[_myTableView reloadData];
} completion:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) {
[_myTableView reloadData];
}];
}

in your rotation func:
self.view.layoutIfNeeded()

Related

iOS - AccessoryView changes the size of custom separator

I have a grouped tableview and at first I wanted to remove the top and bottom separator. I looked around and found a solution that worked great form me. It was by adding a UIView to the bottom of the cell to act as the separator. Now it looks amazing. But the problem I faced is when I set the AccessoryView of the cell , because for some reason when I select the cell , my custom separator change its width . Here's a representation of the problem :
this is when not selected
this is when selected :
Note that the custom separator already has constraint .
Any suggestions please ?
Edit:
Here's how I set the accessoryView :
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if let cell = tableView.cellForRow(at: indexPath) as? TableViewCell {
let label = UILabel()
label.text = "x"
label.sizeToFit()
label.font = UIFont.systemFont(ofSize: 13, weight: .medium)
if(cell.accessoryView == nil){
cell.accessoryView = label
}else{
cell.accessoryView = nil
}
}
}
that's it and everything else is just a simple tableview with rows and section , I also set the separator to none in storyboard.
Edit 2 :
This is the separator constraints :
You need to change your trailing constraint. Instead of ContentView add trailing constraint to cell. Remove trailing constraint on separator view and add constraints as in image.
In iOS 13+, I had to change the code to draw bottom border on the cell instead of the cell's contentView. I do it in awakeFromNib in the Cell class.
override func awakeFromNib() {
super.awakeFromNib()
addBorder(borderType: .bottom)
}
func addBorder(borderType: BorderType, width: CGFloat = 1.0, color: UIColor = .darkGray) {
// figure out frame and resizing based on border type
var autoresizingMask: UIView.AutoresizingMask
var layerFrame: CGRect
switch borderType {
case .left:
layerFrame = CGRect(x: 0, y: 0, width: width, height: self.bounds.height)
autoresizingMask = [ .flexibleHeight, .flexibleRightMargin ]
case .right:
layerFrame = CGRect(x: self.bounds.width - width, y: 0, width: width, height: self.bounds.height)
autoresizingMask = [ .flexibleHeight, .flexibleLeftMargin ]
case .top:
layerFrame = CGRect(x: 0, y: 0, width: self.bounds.width, height: width)
autoresizingMask = [ .flexibleWidth, .flexibleBottomMargin ]
case .bottom:
layerFrame = CGRect(x: 0, y: self.bounds.height - width, width: self.bounds.width, height: width)
autoresizingMask = [ .flexibleWidth, .flexibleTopMargin ]
}
// look for the existing border in subviews
var newView: UIView?
for eachSubview in self.subviews {
if eachSubview.tag == borderType.rawValue {
newView = eachSubview
break
}
}
// set properties on existing view, or create a new one
if newView == nil {
newView = UIView(frame: layerFrame)
newView?.tag = borderType.rawValue
self.addSubview(newView!)
} else {
newView?.frame = layerFrame
}
newView?.backgroundColor = color
newView?.autoresizingMask = autoresizingMask
}

Add button overlay on UITableViewController with use static cells

I try to add button overlay on UITableViewController with static cells. But i get this result, button is working, but i not see result of search:
I'm trying to get this result:
I want to button was always at the bottom regardless of scrolling up or down.
In my code i use framework InstantSearch:
import UIKit
import InstantSearch
import WARangeSlider
class SearchTableViewController: UITableViewController {
#IBOutlet weak var resultButton: StatsButtonWidget!
override func viewDidLoad() {
super.viewDidLoad()
resultButton.frame = CGRect(x: 0, y: 0, width: 150, height: 60)
navigationController?.view.addSubview(resultButton)
InstantSearch.shared.registerAllWidgets(in: self.view)
LayoutHelpers.setupResultButton(button: resultButton)
resultButton.addTarget(self, action: #selector(resultButtonClicked), for: .touchUpInside)
}
}
How can i add button overlay on bottom in UITableViewController? Me need use only UITableViewController, not UIViewController with TableView.
You could directly add the button to the UITableView without AutoLayout, and make sure TableView's delegate is the controller, like:
override func viewDidLoad() {
super.viewDidLoad()
self.button.frame = CGRect(x: 0, y: self.tableView.frame.size.height - 50, width: self.tableView.frame.width, height: 50)
self.tableView.addSubview(self.button)
self.tableView.delegate = self
}
Then you are able to fix the button's position by UIScrollView delegate (UITableViewDelegate inherited from this) while TableView is scrolling:
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if (scrollView == self.tableView) {
let originY = scrollView.frame.size.height - self.button.frame.size.height + scrollView.contentOffset.y
self.button.frame = CGRect(x: 0, y: originY, width: scrollView.frame.width, height: self.button.frame.size.height)
}
}
Alternatively, if you want to position the button by AutoLayout, just define a NSLayoutConstraint property, and bind it to button's bottom space constraint to its super view. Then adjust the constraint's constant value by same mechanism in scrollViewDidScroll function.
You can just add an view at the bottom of your tableview.
override func viewDidLoad() {
super.viewDidLoad()
addResultButtonView()
}
private func addResultButtonView() {
let resultButton = UIButton()
resultButton.backgroundColor = .red
resultButton.setTitle("Hello", for: .normal)
tableView.addSubview(resultButton)
// set position
resultButton.translatesAutoresizingMaskIntoConstraints = false
resultButton.leftAnchor.constraint(equalTo: tableView.safeAreaLayoutGuide.leftAnchor).isActive = true
resultButton.rightAnchor.constraint(equalTo: tableView.safeAreaLayoutGuide.rightAnchor).isActive = true
resultButton.bottomAnchor.constraint(equalTo: tableView.safeAreaLayoutGuide.bottomAnchor).isActive = true
resultButton.widthAnchor.constraint(equalTo: tableView.safeAreaLayoutGuide.widthAnchor).isActive = true
resultButton.heightAnchor.constraint(equalToConstant: 50).isActive = true // specify the height of the view
}

How to add a view on top of UITableView that scrolls together, but stick to top after scrolling

I have a UIView with height of 100 pixels that's on top of my UITableView. When I scroll up I want the UIView to scroll together with my UITableView as if it's part it. When 50 pixels of my UIView is hidden from scrolling up, I want to pin the UIView at the top while I continue scrolling up. How can this be achieved? I tried using changing my UIView's top NSLayoutConstraint constant equal to my tableview's content offset, but they don't scroll at the same speed.
First make sure your tableView is grouped:
self.tableView = UITableView(frame: CGRect(x: 0, y: (self.navigationController?.navigationBar.frame.maxY)!, width: self.view.bounds.size.width, height: (self.view.bounds.size.height - (self.navigationController?.navigationBar.frame.maxY)!)), style: .grouped)
self.tableView.delegate = self
self.tableView.dataSource = self
self.view.addSubview(self.tableView)
Then you need to add the UIView into the subview of your tableView:
self.myView = UIView()
self.myView.backgroundColor = UIColor.green
self.myView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: 100)
self.tableView.addSubview(self.myView)
Add a header of height 100 for your tableView's first section so that your cells are at right place:
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 100
}
Then adjust the frame of your UIView when scrolling:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offset = scrollView.contentOffset.y
if(offset > 50){
self.myView.frame = CGRect(x: 0, y: offset - 50, width: self.view.bounds.size.width, height: 100)
}else{
self.myView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: 100)
}
}
Demo:
If I understand you'r question correctly, You can do it by implementing table view scrollViewDidScroll: method like this
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
static CGFloat previousOffset;
CGRect rect = self.yourUIView.frame;
//NSLog you'r UIView position before putting any condition
// NSLog(#"Origin %f",rect.origin.y);
rect.origin.y += previousOffset - scrollView.contentOffset.y;
previousOffset = scrollView.contentOffset.y;
//assuming you'r UIView y position starts from 0
//Before setting the condition please make sure to run without any
//condition if not working
if(rect.origin.y>=-50 && rect.origin.y<=0){
self.yourUIView.frame = rect;
}
}
Hope it helps...
What you need is to implement the viewForHeader inSection method for your tableView (remember to make your ViewController implementing the tableviewDelegate protocol) and once you've got it you should set your tableViewStyle to UITableViewStylePlain
Share your code if you are interested in more help.
Source: UITableView with fixed section headers
I got the same problem with
navigationItem.largeTitleDisplayMode = .always
navigationBar.prefersLargeTitles = true
and
tableView.contentInset = UIEdgeInsets(top: 40, left: 0, bottom: 0, right: 0)
For me nothing from any above options can help but I realised that you can just call
tableView.setContentOffset(CGPoint(x: 0, y: -tableView.contentInset.top), animated: false)
in viewDidload() and problem gone! :)
Totally forgot about this method and spent too much time for this creepy behavior.
Good Luck!

my initial problems with UIScrollView now appear to be related to autolayout

For my first challenge using UIScrollView I modified this example to make UIScrollView display not just another background colour but another UIView and UILabel on each page. But I could have just as easily chosen to display objects like UITableView, UIButton or UIImage.
Potentially, UIScrollView could be much more than a giant content view where users scroll from one part to the next, e.g., some pages might have a UIButton that takes a user to a specific page, the same way we use books.
Code Improvements
My question has evolved since I first posted it. Initially the labels piled up on page 1 (as shown below) but this has now been corrected. I also included this extension to make the font larger.
Further improvement ?
As the code evolved I became more aware of other issues e.g. iPhone 5 images (below) appear differently on iPhone 7 where the UILabel is centred but not the UIView. So my next challenge is possibly to learn how to combine UIScrollView with Autolayout. I invite anyone to spot other things that might be wrong.
ViewController.swift (corrected)
import UIKit
class ViewController: UIViewController,UIScrollViewDelegate {
let scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: 320, height: 480))
var views = [UIView]()
var lables = [UILabel]()
var colors:[UIColor] = [UIColor.red, UIColor.magenta, UIColor.blue, UIColor.cyan, UIColor.green, UIColor.yellow]
var frame: CGRect = CGRect.zero
var pageControl: UIPageControl = UIPageControl(frame: CGRect(x: 50, y: 500, width: 200, height: 50))
override func viewDidLoad() {
super.viewDidLoad()
initialiseViewsAndLables()
configurePageControl()
scrollView.delegate = self
self.view.addSubview(scrollView)
for index in 0..<colors.count {
frame.origin.x = self.scrollView.frame.size.width * CGFloat(index)
frame.size = self.scrollView.frame.size
self.scrollView.isPagingEnabled = true
views[index].frame = frame
views[index].backgroundColor = colors[Int(index)]
views[index].layer.cornerRadius = 20
views[index].layer.masksToBounds = true
lables[index].frame = frame
lables[index].center = CGPoint(x: (view.frame.midX + frame.origin.x), y: view.frame.midY)
lables[index].text = String(index + 1)
lables[index].defaultFont = UIFont(name: "HelveticaNeue", size: CGFloat(200))
lables[index].textAlignment = .center
lables[index].textColor = .black
let subView1 = views[index]
let subView2 = lables[index]
self.scrollView .addSubview(subView1)
self.scrollView .addSubview(subView2)
}
print(views, lables)
self.scrollView.contentSize = CGSize(width: self.scrollView.frame.size.width * CGFloat(colors.count), height: self.scrollView.frame.size.height)
pageControl.addTarget(self, action: Selector(("changePage:")), for: UIControlEvents.valueChanged)
}
func initialiseViewsAndLables() {
// Size of views[] and lables[] is linked to available colors
for index in 0..<colors.count {
views.insert(UIView(), at:index)
lables.insert(UILabel(), at: index)
}
}
func configurePageControl() {
// Total number of available pages is based on available colors
self.pageControl.numberOfPages = colors.count
self.pageControl.currentPage = 0
self.pageControl.backgroundColor = getColour()
self.pageControl.pageIndicatorTintColor = UIColor.black
self.pageControl.currentPageIndicatorTintColor = UIColor.green
self.view.addSubview(pageControl)
}
func getColour() -> UIColor {
let index = colors[pageControl.currentPage]
return (index)
}
func changePage(sender: AnyObject) -> () {
scrollView.setContentOffset(CGPoint(x: CGFloat(pageControl.currentPage) * scrollView.frame.size.width, y: 0), animated: true)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
pageControl.currentPage = Int(pageNumber)
pageControl.backgroundColor = getColour()
}
}
Extension
extension UILabel{
var defaultFont: UIFont? {
get { return self.font }
set { self.font = newValue }
}
}
The centre point of the lable on each frame must be offset by the origin of the content view (as Baglan pointed out). I've modified the following line of code accordingly.
lables[Int(index)].center = CGPoint(x: (view.frame.midX + frame.origin.x), y: view.frame.midY)

Unable to change contentSize of UIScrollview in WKWebView

I'm trying to add a little bit of extra height to the content of a UIScrollView that is within a WKWebView after it loads by adjusting the contentSize property.
I can modify this property, but it somehow keeps changing back to its original size by the time the next layout/display refresh hits.
To test this even further, I attempted to change contentSize in scrollViewDidScroll. Whenever you scroll to the bottom, you can see for a fraction of a second that it's trying add the extra space and keeps reverting back.
I can't reproduce this issue with UIWebView. It works just fine there. Perhaps some changes were added to WKWebView recently? I'm using Xcode 8 and testing on iOS 9/10.
Given my ineptitude with Dropbox I felt badly so put the attached together to try and help you out. If you change the contentInset property of the WKWebView's scrollView rather than contentSize, this seems to work quite well. I agree with you that while you might be able temporarily to change the content size of the scrollView, it reverts quickly; moreover, there are no delegate methods either for UIScrollView or WKWebView that I can find that you might override to counteract this.
The following sample code has a web page and some buttons that allow you to increase or decrease the top and bottom contentInset and animating you to the appropriate point on the scrollView.
import UIKit
import WebKit
class ViewController: UIViewController {
var webView : WKWebView!
var upButton : UIButton!
var downButton : UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let webFrame = CGRect(origin: CGPoint(x: 100, y: 100), size: CGSize(width: self.view.frame.width - 200, height: self.view.frame.height - 200))
webView = WKWebView(frame: webFrame)
webView.load(URLRequest(url: URL(string: <PUT RELEVANT URL STRING (NB - THAT YOU ARE SURE IS VALID) HERE>)!))
webView.backgroundColor = UIColor.red
webView.scrollView.contentMode = .scaleToFill
self.view.addSubview(webView)
func getButton(_ label: String) -> UIButton {
let b : UIButton = UIButton()
b.setTitle(label, for: .normal)
b.setTitleColor(UIColor.black, for: .normal)
b.layer.borderColor = UIColor.black.cgColor
b.layer.borderWidth = 1.0
return b
}
let upButton = getButton("Up")
let downButton = getButton("Down")
upButton.frame = CGRect(origin: CGPoint(x: 25, y: 25), size: CGSize(width: 50, height: 50))
downButton.frame = CGRect(origin: CGPoint(x: 25, y: 100), size: CGSize(width: 50, height: 50))
upButton.addTarget(self, action: #selector(increaseContentInset), for: .touchUpInside)
downButton.addTarget(self, action: #selector(decreaseContentInset), for: .touchUpInside)
self.view.addSubview(webView)
self.view.addSubview(upButton)
self.view.addSubview(downButton)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func increaseContentInset() -> Void {
guard let _ = webView else { return }
webView.scrollView.contentInset = UIEdgeInsetsMake(webView.scrollView.contentInset.top + 100, 0, webView.scrollView.contentInset.bottom + 100, 0)
webView.scrollView.setContentOffset(CGPoint(x: webView.scrollView.contentInset.left, y: -1 * webView.scrollView.contentInset.top), animated: true)
}
func decreaseContentInset() -> Void {
guard let _ = webView else { return }
webView.scrollView.contentInset = UIEdgeInsetsMake(webView.scrollView.contentInset.top - 100, 0, webView.scrollView.contentInset.bottom - 100, 0)
webView.scrollView.setContentOffset(CGPoint(x: webView.scrollView.contentInset.left, y: -1 * webView.scrollView.contentInset.top), animated: true)
}
}
I hope that helps. If you need an answer based specifically on setting the content size then let me know, but I think this is the best option.

Resources