UIScrollView scrollable area not updating with scrollView frame constraint update - swift

I'm updating a frame constraint
scrollView.top Equal container.top
by subtracting from the constant, then calling layoutIfNeeded()
The scrollview's frame updates fine, and the content comes with it, but in the new area that the scrollview has acquired (above the scrollview) it does not fire scroll events when dragging. The old area works.
I've tried updating the contentOffset, but that effectively scrolls the content up inside the scrollview instead of expanding the scrollable area
I'm updating the contentSize, but it seems like problem is where the contentSize starts from
I've tried updating the contentInset, that still just moves the content around without updating the scrollable area
Maybe there is a property that needs to be updated but I can't find it
The end goal here is to programmatically increase the size of a scrollView
here is scrollViewDidScroll, where I'm updating the constraint
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let newVal:CGFloat = -120.0
DispatchQueue.main.async { [unowned self] in
self.feedTableViewTopConstraint.constant = newVal
self.view.layoutIfNeeded()
}
}

You should call
setNeedsLayout()
instead and if you want the layoutIfNeeded() to happen in the same loop then you can call it immediately after you called setNeedsLayout()

Related

NSScrollView not scrolling

I have a form in a Mac app that needs to scroll. I have a scrollView embedded in a ViewController. I have the scrollView assigned with an identifier that links it to its own NSScrollView file. The constraints are set to the top, right, and left of the view controller, it also has the hight constraint set to the full height of the ViewController.
Here is my code:
import Cocoa
class ScrollView: NSScrollView {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// Drawing code here.
NSRect documentView.NSMakeSize(0, 0, 1058.width, 1232.height)
}
override func scrollWheel(with event: NSEvent) {
switch event.phase {
case NSEvent.Phase.began:
Swift.print("Began")
// case NSEvent.Phase.changed:
// Swift.print("Changed")
case NSEvent.Phase.ended:
Swift.print("Ended")
default:
break
}
switch event.momentumPhase {
case NSEvent.Phase.began:
Swift.print("Momentum Began")
// case NSEvent.Phase.changed:
// Swift.print("Momentum Changed")
case NSEvent.Phase.ended:
Swift.print("Momentum Ended")
default:
break
}
super.scrollWheel(with: event)
}
I cant seem to get my app to scroll at all. I think I am not setting the frame correctly. What is the best way to do set the frame correctly? Am I coding the NSScrollView correctly?
I think you are making your life very hard because you are doing things that are not exactly recommended by Apple. First of all, you should not subclass NSScrollView. Rather you should read first Introduction to Scroll View Programming Guide for Cocoa by Apple to understand how you should create the correct hierarchy of views for an NSScrollView to work correctly.
A second recommendation is for you to check this nice article about how you should set up an NSScrollView in a playground, so that you can play with the code you want to implement.
Third, using Autolayout and NSScrollView has caused a lot of grief to a lot of people. You need to set up the AutoLayout just right, so that everything is going to work as expected. I recommend that you check this answer by Ken Thomases, which clearly explains how you need to set up auto layout constraints for an NSScrollView to work properly.
I just got over the "hump" with a NSScrollView inside a NSWindow. In order for scrolling to occur the view inside the NSScrollview needs to be larger than the content window. That's hard to set with dynamic constraints. Statically setting the inner view to a larger width/height than the window "works" but the static sizes usually are not what you want.
Here is my interface builder view hierarchy and constraints, not including the programmatically added boxes
In my app the user is adding "boxes" (custom draggable views) inside the mainView, which is inside a scrollview in a NSwindow.
Here's the functionality I wanted:
If I expanded the NSWindow, I wanted the mainView inside the scrollview to expand to fill the whole window. No scrolling needed in this case if all the boxes are visible.
If I shrank the NSWindow, I wanted the mainView inside the scrollview to shrink just enough to include all my mainView subviews ("boxes"), but not any further (i added a minBorder of 20). This results in scrolling if a box's position is further right/up than the nswindow's width/height.
I found the trick is to calculate the size of the mainView I want based on the max corner of each draggable boxview, or the height/width of the content frame of the nswindow, whichever is larger.
Below is my code, including some debugging prints.
Be careful of which subviews you use to calculate the max size. If you include a subview that's dynamically attached to the right/top of the window, then your window will never shrink. If you add +20 border to that, you might infinite loop. Not a problem in my case.
extension MapWindowController: NSWindowDelegate {
func windowDidEndLiveResize(_ notification: Notification) {
if let frame = window?.frame, let content = window?.contentRect(forFrameRect: frame) {
print("window did resize \(frame)")
var maxX: CGFloat = content.width
var maxY: CGFloat = content.height
for view in mainView?.subviews ?? [] {
let frameMaxX = view.frame.maxX + minBorder
let frameMaxY = view.frame.maxY + minBorder
if frameMaxX > maxX {
maxX = frameMaxX
}
if frameMaxY > maxY {
maxY = frameMaxY
}
}
print("view maxX \(maxX) maxY \(maxY)")
print("window width \(content.width) height \(content.height)")
mainView?.setFrameSize(NSSize(width: maxX, height: maxY))
}
}
}

UIImageView is not auto height in StackView with TableViewCell

This is the view hierarchy
I want the PhotoImgView auto height depends on the Image size
The image is download from server
I use KingFisher to download the image
when download finished, I set PhotoImgView's height constraint, and do layoutIfNeeded() in the cell class
but it's not update UI immediately
when I scroll to another cell, and let the cell invisible, and then scroll back, the cell would be right
How can I do this?
Same issue with the collectionView, I set collectionview's height constraint after collectionview.reloaData and get collectionview.contentSize.height
Try this:
Replace your current layoutIfNeeded() with this:
DispatchQueue.main.async {
self.layoutIfNeeded()
}
Try to call setNeedsLayout() before layoutIfNeeded().
To get right result for collection view height you can try:
collectionView.reloadData()
collectionView.setNeedsLayout()
collectionView.layoutIfNeeded()
collectionView.collectionViewLayout.invalidateLayout()

Unable to remove axis animation from `UIStackView`

I have an UIStackView build in interface builder which changes it's axis property from vertical to horizontal when it's superview rotates from portrait to landscape. The issue is that this results in an animation of it's two arranged subviews, where one of those views overlaps the other view while transitioning to the new position.
In my case I would like to remove only that particular animation and force the view to it's end position right away.
I have tried to remove all animation on from the stackview layer in my VC:
public override func willTransition(to newCollection: UITraitCollection,
with coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animate(alongsideTransition: {
_ in
// The first subview is `UIStackView`
self.view.subviews[0].layer.removeAllAnimations()
})
super.willTransition(to: newCollection, with: coordinator)
}
And I observed the animation keys when the axis property is changed, because that seems to happen somewhere during the transition (set automatically by interface builder). Unfortunately I had no luck with it, because the layer returns nil for animationKeys on the stackview and its subviews/arrangedSubviews.
class StackView : UIStackView {
override var axis: UILayoutConstraintAxis {
didSet { /* here */ }
}
}
That's going to be challenging, I think. There's a nice demo of what it sounds like you're trying to do over here if the axis animation it shows is what you're trying to get rid of, pretty sure that's outside the UIStackView design space.
Pretty sure the best solution to "force the view to it's end position right away" is to in fact have one UIStackView for each axis and move the contents between them on rotation.
You could also try putting a performWithoutAnimation block in your viewWillTransition(to:with:) that calls updateConstraintsIfNeeded on completion? Maybe that would work. I'd go with the two-view idea instead of that though!

Tracking the position of a NSCell on change

I have a NSTableView and want to track the position of its containing NSCells when the tableView got scrolled by the user.
I couldn’t find anything helpful. Would be great if someone can lead me into the right direction!
EDIT:
Thanks to #Ken Thomases and #Code Different, I just realized that I am using a view-based tableView, using tableView(_ tableView:viewFor tableColumn:row:), which returns a NSView.
However, that NSView is essentially a NSCell.
let cell = myTableView.make(withIdentifier: "customCell", owner: self) as! MyCustomTableCellView // NSTableCellView
So I really hope my initial question wasn’t misleading. I am still searching for a way how to track the position of the individual cells/views.
I set the behaviour of the NSScrollView (which contains the tableView) to Copy on Scroll in IB.
But when I check the x and y of the view/cells frame (within viewWillDraw of my MyCustomTableCellView subclass) it remains 0, 0.
NSScrollView doesn't use delegate. It uses the notification center to inform an observer that a change has taken place. The solution below assume vertical scrolling.
override func viewDidLoad() {
super.viewDidLoad()
// Observe the notification that the scroll view sends out whenever it finishes a scroll
let notificationName = NSNotification.Name.NSScrollViewDidLiveScroll
NotificationCenter.default.addObserver(self, selector: #selector(scrollViewDidScroll(_:)), name: notificationName, object: scrollView)
// Post an intial notification to so the user doesn't have to start scrolling to see the effect
scrollViewDidScroll(Notification(name: notificationName, object: scrollView, userInfo: nil))
}
// Whenever the scroll view finished scrolling, we will start coloring the rows
// based on how much they are visible in the scroll view. The idea is we will
// perform hit testing every n-pixel in the scroll view to see what table row
// lies there and change its color accordingly
func scrollViewDidScroll(_ notification: Notification) {
// The data's part of a table view begins with at the bottom of the table's header
let topEdge = tableView.headerView!.frame.height
let bottomEdge = scrollView.bounds.height
// We are going to do hit-testing every 10 pixel. For best efficiency, set
// the value to your typical row's height
let step = CGFloat(10.0)
for y in stride(from: topEdge, to: bottomEdge, by: step) {
let point = NSPoint(x: 10, y: y) // the point, in the coordinates of the scrollView
let hitPoint = scrollView.convert(point, to: tableView) // the same point, in the coordinates of the tableView
// The row that lies that the hitPoint
let row = tableView.row(at: hitPoint)
// If there is a row there
if row > -1 {
let rect = tableView.rect(ofRow: row) // the rect that contains row's view
let rowRect = tableView.convert(rect, to: scrollView) // the same rect, in the scrollView's coordinates system
let visibleRect = rowRect.intersection(scrollView.bounds) // the part of the row that visible from the scrollView
let visibility = visibleRect.height / rowRect.height // the percentage of the row that is visible
for column in 0..<tableView.numberOfColumns {
// Now iterate through every column in the row to change their color
if let cellView = tableView.view(atColumn: column, row: row, makeIfNecessary: true) as? NSTableCellView {
let color = cellView.textField?.textColor
// The rows in a typical text-only tableView is 17px tall
// It's hard to spot their grayness so we exaggerate the
// alpha component a bit here:
let alpha = visibility == 1 ? 1 : visibility / 3
cellView.textField?.textColor = color?.withAlphaComponent(alpha)
}
}
}
}
}
Result:
Update based on edited question:
First, just so you're aware, NSTableCellView is not an NSCell nor a subclass of it. When you are using a view-based table, you are not using NSCell for the cell views.
Also, a view's frame is always relative to the bounds of its immediate superview. It's not an absolute position. And the superview of the cell view is not the table view nor the scroll view. Cell views are inside of row views. That's why your cell view's origin is at 0, 0.
You could use NSTableView's frameOfCell(atColumn:row:) to determine where a given cell view is within the table view. I still don't think this is a good approach, though. Please see the last paragraph of my original answer, below:
Original answer:
Table views do not "contain" a bunch of NSCells as you seem to think. Also, NSCells do not have a position. The whole point of NSCell-based compound views is that they're much lighter-weight than an architecture that uses a separate object for each cell.
Usually, there's one NSCell for each table column. When the table view needs to draw the cells within a column, it configures that column's NSCell with the data for one cell and tells it to draw at that cell's position. Then, it configures that same NSCell with the data for the next cell and tells it to draw at the next position. Etc.
To do what you want, you could configure the scroll view to not copy on scroll. Then, the table view will be asked to draw everything whenever it is scrolled. Then, you would implement the tableView(_:willDisplayCell:for:row:) delegate method and apply the alpha value to the cells at the top and bottom edges of the scroll view.
But that's probably not a great approach.
I think you may have better luck by adding floating subviews to the scroll view that are partially transparent, with a gradient from fully opaque to fully transparent in the background color. So, instead of the cells fading out and letting the background show through, you put another view on top which only lets part of the cells show through.
I just solved the issue by myself.
Just set the contents view postsBoundsChangedNotifications to true and added an observer to NotificationCenter for NSViewBoundsDidChange. Works like a charm!

Scrolling ScrollView even when ContentView has the same size

I have a ScrollView defined with autolayout : it has a contentView, in which there's some elements. The scrollView has constraints with other views to set it's size, and 4 constraints with the contentView (up, down, left, right, each with constant = 0). The contentView has a defined size, the same size as the scrollView.
I want my scrollView to scroll and bounce (I overrided the scrollViewDidScroll method), but the problem is the scrollView is not scrolling if the contentView has the same size as it (which is logic, since there's no content to scroll, but I want it to bounce).
How can I make my scrollView scrolling ?
Try setting to your scrollView:
scrollView.alwaysBounceHorizontal = true
scrollView.alwaysBounceVertical = true
or in Interface Builder, make sure you've checked options: