Check if view is visible on the screen [Swift 5.1] - swift

I have this View Controller that contains the bigTitle label (Please ignore the right-to-left):
In this situation, (bigTitle is visible), I want the top Navigation Bar to not contain any text (but still be visible!)
But when the user scrolls down in the scrollView and the bigTitle is not visible anymore, I want the Navigation Bar to contain the text that was in the bigTitle, in this case it's Welcome to our app!
This is my current code (right now it's not completed and it's in the viewDidLoad()) (feel free to change anything you want):
_ = Timer.scheduledTimer(withTimeInterval: 0.05, repeats: true, block: { (time) in
// If bigTitle is visible on the screen
if true {
self.bigTitle.alpha = 1
self.navBar.title = "" // navBar is my Navigation Bar reference
} else {
self.bigTitle.alpha = 0
self.navBar.title = self.bigTitle.text
}
})
Thanks!

Don't use a timer to track what happens when scrolling; use the scroll view's delegate. As the user scrolls, you are notified in the delegate method. Examine the label's frame; convert it to window coordinates to discover whether it is off the screen.

Related

UITextView Moves to Left on Keyboard Show

I have an app with a build target of IOS 14 that is causing a problem regarding automatic positioning of the view on keyboard show.
I have a UITextView that is draggable and can be positioned partially outside of the main view that it sits within. If the field is large enough then it will extend beyond the parent view and safe area also. The parent view has clipsToBounds set as true so the overflow of the text view is not visible.
The problem is when the text field is positioned so that its right hand side is outside of the safe area and the keyboard is presented, the screen automatically scrolls left to include the far right edge of the text view, even though it is not visible due to clipsToBounds being set on its parent. I need to disable the behaviour that is causing this to happen but can't find anything that covers this for UIKit.
See below for a visual example. Can anybody please help?
Image 1
Image 2
Edit:
The structure of the screen is:
View Controller:
.....UICollectionView:
..........UICollectionViewCell:
...............UIView:
....................Elements (UITextView in this case)
func calculateCarouselOffset(formHeight: CGFloat) -> CGAffineTransform {
let carouselOffset: CGAffineTransform!
let currentElementMaxY = returnCurrentElementMaxY()
let elementMaxYTransformRemoved = currentElementMaxY + -self.scalingCarousel.transform.ty
let newFormOriginY = safeAreaFrame.height - formHeight
let topOfFormMargin: CGFloat = 20
if (newFormOriginY - topOfFormMargin) < elementMaxYTransformRemoved {
// Form will overlap element - move carousel view to compensate
let oldToNewLocDist = (newFormOriginY - topOfFormMargin) - currentElementMaxY
let moveScreenBy = self.scalingCarousel.transform.ty + oldToNewLocDist
carouselOffset = CGAffineTransform(translationX: 0, y: moveScreenBy)
} else {
// Form will not overlap element - reset carousel view
carouselOffset = self.formDeactivate
}
return carouselOffset
}
And it is called as below:
func textViewDidChage() {
let backgorundTransform = calculateCarouselOffset(formHeight: currentElementFormHeight)
let modifyBackground = UIViewPropertyAnimator(duration: 0.2, curve: .linear, animations: {
self.scalingCarousel.transform = backgorundTransform
})
modifyBackground.startAnimation()
}
It looks like this is (possibly new?) built-in behaviour for text fields. I reproduced this both with a collection view controller and a view controller holding a collection view. The text field moves itself to visible like this:
I found this by adding a symbolic breakpoint on contentOffset and then making a field editable - there are a lot of calls before you get to this point because it's also adjusting things for the keyboard coming up.
Unfortunately in your case, I think the scroll view is moving the text field's visible bounds into the visible area, which means you're scrolling horizontally since the text field is off screen.
You can't override scrollTextFieldToVisibleIfNecessary as it is private API. There are probably some hacks you can do by overriding becomeFirstResponder but they seem quite likely to either not work, or break other things.

Swift - Programmatically refresh constraints

My VC starts with stackView attached with Align Bottom to Safe Area .
I have tabBar, but in the beginning is hidden tabBar.isHidden = true.
Later when the tabBar appears, it hides the stackView
So I need function that refresh constraints after tabBar.isHidden = false
When I start the app with tabBar.isHidden = false the stackView is shown properly.
Tried with every function like: stackView.needsUpdateConstraints() , updateConstraints() , setNeedsUpdateConstraints() without success.
Now I'm changing the bottom programatically, but when I switch the tabBarIndex and return to that one with changed bottom constraints it detects the tabBar and lifts the stackView under another view (which is not attached with constraints). Like is refreshing again the constraints. I'm hiding and showing this stackView with constrains on/off screen.
I need to refresh constraints after tabBar.isHidden = false, but the constraints don't detect the appearance of the tabBar.
As I mention switching between tabBars fixes the issue, so some code executes to detecting tabBar after the switch. Is anyone know this code? I tried with calling the methods viewDidLayoutSubviews and viewWillLayoutSubviews without success... Any suggestions?
This amateur approach fixed my bug... :D
tabBarController!.selectedIndex = 1
tabBarController!.selectedIndex = 0
Or with an extension
extension UITabBarController {
// Basically just toggles the tabs to fix layout issues
func forceConstraintRefresh() {
// Get the indices we need
let prevIndex = selectedIndex
var newIndex = 0
// Find an unused index
let items = viewControllers ?? []
find: for i in 0..<items.count {
if (i != prevIndex) {
newIndex = i
break find
}
}
// Toggle the tabs
selectedIndex = newIndex
selectedIndex = prevIndex
}
}
Usage (called when switching dark / light mode):
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
tabBarController?.forceConstraintRefresh()
}
If you want to update view's layout, you can try layoutIfNeeded() function.
after updating stackView constraints call this method:
stackView.superview?.layoutIfNeeded()
Apple's Human Interface Guidelines indicate that one should not mess around with the Tab Bar, which is why (I'm guessing) setting tabBar.isHidden doesn't properly update the rest of the view hierarchy.
Quick searching comes up with various UITabBarController extensions for showing / hiding the tab bar... but they all appear to push the tabBar down off-screen, rather than setting its .isHidden property. May or may not be suitable for your use.
I'm assuming from your comments that your VC in tab index 0 has a button (or some other action) to show / hide the tabBar?
If so, here is an approach that may do the job....
Add this enum in your project:
enum TabBarState {
case toggle, show, hide
}
and put this func in that view controller:
func showOrHideTabBar(state: TabBarState? = .toggle) {
if let tbc = self.tabBarController {
let b: Bool = (state == .toggle) ? !tbc.tabBar.isHidden : state == .hide
guard b != tbc.tabBar.isHidden else {
return
}
tbc.tabBar.isHidden = b
view.frame.size.height -= 0.1
view.setNeedsLayout()
view.frame.size.height += 0.1
}
}
You can call it with:
// default: toggles isHidden
showOrHideTabBar()
// toggles isHidden
showOrHideTabBar(state: .toggle)
// SHOW tabBar (if it's hidden)
showOrHideTabBar(state: .show)
// HIDE tabBar (if it's showing)
showOrHideTabBar(state: .hide)
I would expect that simply pairing .setNeedsLayout() with .layoutIfNeeded() after setting the tabBar's .isHidden property should do the job, but apparently not.
The quick frame height change (combined with .setNeedsLayout()) does trigger auto-layout, though, and the height change is not visible.
NOTE: This is the result of very brief testing, on one device and one iOS version. I expect it will work across devices and versions, but I have not done complete testing.

How to programmatically add textField to a scroll view

I have a button on my storyboard. This button is inside a view and that view is inside a scroll view.
What I am trying to do sounds relatively simple: When the button is pressed, the button moves down a little bit and a textField appears where the button had previously been.
However, what happens is the button animates, but then returns to its original position, instead of staying moved, and the textField appears as it should.
Because the position of the appearing textField is dependent on the position of the button, pressing the button multiple times simply places a bunch of textfields on top of each other.
Here is a picture of what happens:
my Screen:
Here is the code I am running when the button is pressed:
#IBAction func addIngredientButtonPressed(sender: UIButton) {
contentView.bounds.size.height += addIngredientLabel.bounds.height
scrollView.contentSize.height += addIngredientLabel.bounds.height
//Create Text Field and Set Initial Properties
let newIngredientTextField = UITextField(frame: CGRectMake(self.addIngredientLabel.frame.minX as CGFloat, self.addIngredientLabel.frame.midY as CGFloat, self.addIngredientLabel.bounds.width,self.addIngredientLabel.bounds.height * 0.60))
newIngredientTextField.font = UIFont.systemFontOfSize(15.0)
newIngredientTextField.placeholder = "ADD INGREDIENT HERE"
newIngredientTextField.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left
newIngredientTextField.alpha = 0.0
scrollView.addSubview(newIngredientTextField)
UIView.animateWithDuration(0.5) { () -> Void in
self.addIngredientLabel.center.y += self.addIngredientLabel.bounds.height
newIngredientTextField.alpha = 1.0
}
}
Note:** the length is also being added successfully to the screen, but the button is not staying moved. So in the screenshot above you can indeed scroll up and down **
I noticed that if you comment out the top 2 lines of code, the ones that add height to the contentView and the scrollView, you get almost the right behavior. The button moves and stays moved, the textField appears in the right spot, but if you keep pressing, it won't let you add more textFields than the screen size will hold.
Here is a picture of what happens if you comment out the top two lines. The button won't do anything more if you keep pressing it more:
screen filled:
I found lots of tutorials that tell you how to add more content than can fit into one screen using the storyboard and setting the inferred metrics to free form, but I have not found anyone trying to add elements dynamically like I am.
You appear to have a contentView -- presumably a direct subview of your scrollView, but you're adding the newIngredientTextField directly to your scrollView rather than to your contentView.
When you increase the bounds.size.height of the contentView, it decreases its frame.origin.y by half as much (to keep its center in the same place). As your original button is presumably a subview of this contentView, that will cause it to move independently of the newly-added text field.
In other words, write:
contentView.frame.size.height += addIngredientLabel.bounds.height
rather than
contentView.bounds.size.height += addIngredientLabel.bounds.height
and
contentView.addSubview(newIngredientTextField)
rather than
scrollView.addSubview(newIngredientTextField).

Reveal UISearchBar when UITableView is dragged from the first row

My search bar is at the top of the screen, hiding underneath the navigation bar. I'd like to show the search bar when the user is panning, only when the table view is at the top (at row 0). Can someone explain this?
I've tried using the pan gesture, but then the search bar will show every time I pan downwards.
func showSearchBar(recognizer: UIPanGestureRecognizer) {
if recognizer.state == .Changed {
let translation = recognizer.translationInView(view)
if searchBarConstraint.constant < searchBar.bounds.height {
searchBarConstraint.constant += translation.y
}
}
}
As UITableView is a subclass of UIScrollView you can use its contentOffset to determine whether the table view is at the top or not:
let isAtTop = tableView.contentOffset.y == 0
Of course this only works it you have not set the default contentOffset to another point. Otherwise you would have to check for the y value of your default contentOffset.

Change button background color dynamically like progress bar

I am trying to implement buttons with changeable background colors in Swift. But I do not want to change color of whole button. I want it to change like progress bar. For example, there will be a specific time value, and background color of button should change from right to left with animation in that time.
I saw apps like that. Can anyone give a clue for how to do that?
Don't be constrained by the idea that a button is only a UIButton. A button can be a view with a gesture recogniser, or a view with a transparent button over the top of it. It could be a button with a background image that you keep updating. There are many options for how to construct what you describe. It depends exactly what effect you want as to how it should be done. Buttons showing progress would often be disabled until progress is complete so you could easily use a progress indication view which is replaced by a 'real' button when progress is complete.
Maybe this helps you.
func changeButtonColors(){
//let myBtn
let timer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: "changeColor", userInfo: nil, repeats: true)
timer.fire()
}
//cloros to iterate over each time
let colorChoice = [UIColor.blackColor(), UIColor.blueColor(), UIColor.redColor()]
var counter = 0 //tracking variable
//this gets called when by the timer
//currently it is supposed to go on forever.
func changeColor(){
//suppose i have the button outlet named myBtn
UIView.animateWithDuration(2.0, animations: { () -> Void in
myBtn.backgroundColor = colorChoice[counter]
if counter < colorChoice.count{
counter++
}else{
counter = 0
//or disable the alert
//timer.invalidate()
}
})
}
Here myBtn is a outlet to the View Controller. We use Timer to trigger the function call at a specific time in our case every 2 second. This can be derived by other app logic.
The called function then iterates over a array of UIColor and applies one to the background of the button or view. The workflow is this. Change things where you require.