Scroll Position of UITextView at the top - swift

I am using swift and want a UITextView to be at the top when the view launches. At the moment when I launch the app the UITextView is scrolled to the end. I have tried looking online and think scrollRangeToVisible might work but do not know how to use it in swift.
import UIKit
class ThirdViewController: UIViewController {
#IBOutlet weak var FunFact: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
FunFact.scrollRangeToVisible(0, 0)
// Do any additional setup after loading the view.
}
}

Add this to your ViewController:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
textView.layoutIfNeeded()
textView.contentOffset = CGPoint.zero
}
This scrolls the UITextView to the top. Since it only knows its size, when it is layouted, "layoutIfNeeded" is needed after you changed the text (i changed it in viewDidLoad).

Try this:
var zeroOffset = CGPoint.zeroPoint
FunFact.contentOffset(zeroOffset)
This should bring the offset to 0 (the offset is an indication of how far the current position is from the initial one)

Related

UIView's animate method not appearing

I am trying to make an app that utilizes some search feature and I am trying to make it so that after the search button is pressed, a view (which contains the search results) moves up from the bottom of the superview and replaces the search view. On the storyboard, the resultsView (of type UIView) is constrained so that its top is equal to the superview's bottom. After the search button is pressed, I would like to animate the view to move up and replace the view already at the bottom of the superview. The problem is, in the viewcontroller's class, when I call the resultsView, the animateWithDuration(NSTimeInterval) that is supposed to be associated with the UIView class is not appearing for me. May this be because the view is already constrained in place? Here is the code, simplified for this post:
import UIKit
import MapKit
class MapViewController: UIViewController, CLLocationManagerDelegate,
MKMapViewDelegate {
#IBOutlet weak var mapView: MKMapView!
#IBOutlet weak var slider: UISlider!
#IBOutlet weak var distanceLabel: UILabel!
#IBOutlet weak var searchButton: UIButton!
#IBOutlet weak var searchView: UIView!
#IBOutlet weak var resultView: UIView!
#IBOutlet weak var resultNameLabel: UILabel!
#IBOutlet weak var resultDistanceLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
self.resultView.isHidden = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func sliderAdjusted(_ sender: Any) {
let int = Int(slider.value)
switch int {
case 1:
distanceLabel.text = "1 mile"
default:
distanceLabel.text = "\(int) miles"
}
}
#IBAction func searchButtonPressed(_ sender: Any) {
/*This is where, after calling a search function which is omitted
from this example, I would like to make the resultsView not
hidden and then animate it to sort of eclipse the search view*/
self.resultView.isHidden = false
self.resultView.animate(withDuration: NSTimeInterval)
/*The above line of code is not actually appearing for me.
After typing "self.resultView." the animate function is not being
given to me as an option for my UIView*/
}
}
I will also attach some images of the view controller so you can sort of get the idea. The results view is not visible in this image because its top is constrained to the superview's bottom, thus it is just out of the visible representation of its superview.
The first image is the view controller with the searchView highlighted. This is the view that I would like to be eclipsed by my resultView after the searchButton is pressed.
The second image is the same view controller with the resultView highlighted. As you can see, its top is constrained to be equal to the superview's bottom. This is the view that I would like to animate upwards into the superview and eclipse the searchView after the search button is pressed.
The methods for all the animate family are all class methods. Which means you call them on the class object not an instance.
You are trying to call
class func animate(withDuration: TimeInterval, animations: () -> Void)
so your code needs to look like
UIView.animate(withDuration: 0.5) {
//the things you want to animate
//will animate with 0.5 seconds duration
}
In the particular case it looks like you are trying to animate the height of resultView so you need an IBOutlet to that constraint. You could call it resultViewHeight.
UIView.animate(withDuration: 0.5) {
self.resultViewHeight.constant = theDesiredHeight
self.layoutIfNeeded()
}
Calling layoutIfNeeded() within the closure is the secret sauce to animating auto layout. Without that the animation will just jump to the and point.

How to randomize UILabel text each time the view controller is showed

How do I make a label in my ViewController have a diffrent string of text each time the view crontroller is shown? Thanks! I'm using Swift 3
Assuming you know how to add UILabel to your ViewController, here is quick sample how to pick random text on start:
class ViewController: UIViewController {
let allTexts = ["Hey", "Hi", "Hello"]
#IBOutlet weak var label: UILabel! //get UILabel from storyboard
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.label.text = self.allTexts[Int(arc4random_uniform(UInt32(self.allTexts.count)))]
}
}
Adding this code to viewWillAppear will change your text anytime ViewController is about to appear - which means if you cover it with another ViewController (let's say popup) and then hide popup - it will change text.
If your prefer to just do it one time - when UIViewController is created put the same code inside viewDidLoad method.

How to let a textfield hover/float above a mapView

I'm making an app which uses MapView, now I've positioned the textfield above the mapview, like on the image. But I really want to fullscreen the mapview and let a textfield float/hover above it. Does anybody know how I can make something like that? I have searched a lot on the internet but couldn't find any clue.. Hope someone can get me starting.
Right, presumably your map view is pinned on all four sides to its superview? Setup your constraints as follows, not how the mapview is not pinned to the text field, but the superview.
http://imgur.com/a/8YmXL
To add the drop shadow, set the following properties on your UITextField:
textField.layer.shadowOpacity = 1.0
textField.layer.shadowRadius = 0.0
textField.layer.shadowColor = UIColor.blackColor().CGColor
textField.layer.shadowOffset = CGSizeMake(0.0, -1.0)
Adjust the settings until you are happy with the look of the shadow.
To dismiss the keyboard when the user pans around the map is very simple. You just need to implement the delegate. Edit your class to look a bit like this:
class MapViewController: UIViewController, MKMapViewDelegate {
#IBOutlet var mapView: MKMapView!
#IBOutlet var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
}
func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
textField.resignFirstResponder()
}
}

(swift) update a number to label will make the view get back to original position

demo image
When I update a number to label will make the view get back to original position.
class ViewController: UIViewController {
#IBOutlet weak var label: UILabel!
#IBOutlet var aview: UIView!
var number = 0
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func plus(sender: UIButton) {
number++
label.text = "number:\(number)"
}
#IBAction func move(sender: AnyObject) {
aview.frame.origin.y -= 20
}
}
I couldn't find the answer on web, please help me to fix this problem.Thank you very much!
Because your xib or Storyboard you set use Autolayout:
So if you don't set constrain system will auto generate it. When you change frame by set frame it effect but when you access to it. It will auto back to old position.
if you don't want it happen. You set in viewDidLoad:
self.view.translatesAutoresizingMaskIntoConstraints = false
Issue is probably related to a constraint reloading when the label reloads.
Instead of setting aview.frame.origin.y -= 20 you should make an outlet to the constraint holding the y position of your aView and then update the constant of that constraint outlet instead.

UILabel Swift/Storyboard returns nil

I created a navigation controller with a view controller inside, containing a label. This label should be changed, when the view controller is loaded on tapping a button.
class ViewController: UIViewController {
#IBOutlet weak var btnEmergency: UIButton!
override func viewWillAppear(animated: Bool) {
self.btnEmergency.backgroundColor = UIColor.redColor();
}
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func btnEmergencyTapped(sender: AnyObject) {
let emergencyViewController = storyboard?.instantiateViewControllerWithIdentifier("EmergencyViewController") as! EmergencyViewController
emergencyViewController.emergencyLabel?.text = "Notruf"
navigationController?.pushViewController(emergencyViewController, animated: true)
}
}
But the label text does not change when loaded. I am relatively new to SWIFT so I try to learn my ropes at the moment using optionals. So I guess the reason is, that the label is not yet instantiated when the view is being loaded on pressing the button. Therefore the default text is being shown and not the text I want to have appear on screen.
I am a little bit stuck at the moment, how to correctly change the label text, when this is an optional. So I guess I cannot expect the label to be there, when I call it. But how do I handle this correctly?
Instead of this, the correct way is to set a property of your emergencyViewController.
In your emergencyViewController viewDidLoad set your label text according to the property set previously.
Anything that you do between initialize of a viewController to viewDidLoad will not take effect.