tableView not scrolling properly inside UIView - swift

I have a tableView made programmatic. I initialised the size of the section and the row. I also put a containerView inside the storyboard which would contain the tableView. My problem is, my table view wouldn't scroll properly.
Here would be my storyboard:
Here would be my outlet for the view in the storyboard:
#IBOutlet weak var trainingDetailsContainerView: UIView!
Here would be my initialized table:
var moduleLessonsTableView: UITableView = {
let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
// tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.backgroundColor = Themes.gray_dec
tableView.sectionHeaderHeight = 35
tableView.rowHeight = 50
tableView.isScrollEnabled = true
tableView.register(TrainingModulesTableViewCell.self, forCellReuseIdentifier: "ModuleLessonsCell")
return tableView
}()
And here is where I would set up my tableView, heights and all:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
moduleLessonsTableView.frame = CGRect(x: 0, y: 0, width: trainingDetailsContainerView.frame.width, height: trainingDetailsContainerView.frame.height)
trainingDetailsContainerView.addSubview(moduleLessonsTableView)
}
I can try putting it in viewWillAppear and the height would render correctly, which had me realizing the bounds of the trainingDetailsContainerView is set before the other views, I think. But the problem with it is it will suddenly pop up. I really don't want that as it looks like a lag from a user's perspective.
Any help would be greatly appreciated.
I also can't tag view lifecycles so I'll just put this here.

Try to add constraints to your table view in viewDidLoad instead of setting frame. Also remove code from viewWillAppear method.
Example code:
override func viewDidLoad() {
super.viewDidLoad()
trainingDetailsContainerView.addSubview(moduleLessonsTableView)
moduleLessonsTableView.topAnchor.constraint(equalTo: trainingDetailsContainerView.topAnchor).isActive = true
moduleLessonsTableView.leadingAnchor.constraint(equalTo: trainingDetailsContainerView.leadingAnchor).isActive = true
moduleLessonsTableView.trailingAnchor.constraint(equalTo: trainingDetailsContainerView.trailingAnchor).isActive = true
moduleLessonsTableView.bottomAnchor.constraint(equalTo: trainingDetailsContainerView.bottomAnchor).isActive = true
}

I have checked - this ViewController should work:
class ViewController: UIViewController {
#IBOutlet weak var trainingDetailsContainerView: UIView!
var moduleLessonsTableView: UITableView = {
let tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.backgroundColor = Themes.gray_dec
tableView.sectionHeaderHeight = 35
tableView.rowHeight = 50
tableView.isScrollEnabled = true
tableView.register(TrainingModulesTableViewCell.self, forCellReuseIdentifier: "ModuleLessonsCell")
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
trainingDetailsContainerView.addSubview(moduleLessonsTableView)
moduleLessonsTableView.topAnchor.constraint(equalTo: trainingDetailsContainerView.topAnchor).isActive = true
moduleLessonsTableView.leadingAnchor.constraint(equalTo: trainingDetailsContainerView.leadingAnchor).isActive = true
moduleLessonsTableView.trailingAnchor.constraint(equalTo: trainingDetailsContainerView.trailingAnchor).isActive = true
moduleLessonsTableView.bottomAnchor.constraint(equalTo: trainingDetailsContainerView.bottomAnchor).isActive = true
}
}

Related

ScrollView scrollToPosition programmaticaly

i have a ViewController that containts View and One more View inside of it
Scroll works fine when i do it by my mouse, but if i use method scrollView.setContentOffset nothing happens.
I tried to check if scroll available using scrollView.delegate = works fine
UiViewController
class WishListViewController: UIViewController {
private lazy var wishListHeaderView: WishListHeaderView = {
let view = WishListHeaderView()
view.delegate = self
return view
}()
}
UiView
class WishListHeaderView: UICollectionReusableView {
private lazy var wishListNavigationView: WishListNavigationView = {
let view = WishListNavigationView()
view.delegate = self
return view
}()
}
Current view with scroll, that is not working
private lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false
return scrollView
}()
private lazy var tabsStackView: UIStackView = {
let stackView = UIStackView()
stackView.distribution = .fill
stackView.axis = .horizontal
stackView.spacing = 8
stackView.backgroundColor = PaletteApp.grayBackgroundButton
return stackView
}()
private func commonInit() {
addSubview(scrollView)
scrollView.snp.makeConstraints { make in
make.left.right.top.bottom.equalToSuperview().inset(16)
make.height.equalTo(38)
}
scrollView.addSubview(tabsStackView)
tabsStackView.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
}
.........
Here is method in this view, debagger shows that i am in this method. And after this if i use print i see scrollviewOffset (100, 0)
func scrollToFirstTab() {
self.scrollView.setContentOffset(CGPoint(x: 100, y: 0), animated: true)
}
Where is a problem? Thank you
Content offset is not the correct method, offset is the gap between content and scroll view itself. For more about content offset, check this answer.
You need to use func scrollRectToVisible(CGRect, animated: Bool).
CGRect.zero to scroll to top.

Tableview y origin not animating properly when navigationItem.titleView is hidden (Swift 5)

I’m trying to get the tableView to move up when the search bar does. Take a look at the problem:
I think I see what the issue is here, but I can't think of a solution. In SearchResultsUpdating I have an animation block:
func updateSearchResults(for searchController: UISearchController) {
UIView.animateKeyframes(withDuration: 1, delay: 0, options: UIView.KeyframeAnimationOptions(rawValue: 7)) {
self.tableView.frame = CGRect(x: 20, y: self.view.safeAreaInsets.top, width:
self.view.frame.size.width-40, height: self.view.frame.size.height -
self.view.safeAreaInsets.top)
}
}
It seems to me that the animation block is only receiving the previous coordinates for the y origin, hence it is animating out of sync. I tried adding a target to the tableView, or navigationBar, or the searchBarTextField instead, but nothing worked.
Any help is appreciated, thanks!
EDIT: After implementing Shawn's second suggestion this was the result:
I can't imagine why it isn't animating smoothly now... very frustrating!
EDIT 2 - Requested Code:
class ViewController: UIViewController{
//City TableView
let cityTableView = UITableView()
let searchVC: UISearchController = {
let searchController = UISearchController(searchResultsController: nil)
searchController.obscuresBackgroundDuringPresentation = true
searchController.searchBar.placeholder = "Search"
return searchController
}()
//viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
//Do any setup for the view controller here
setupViews()
//CityViewController
setupCityViewTableView()
}
//setupViews
func setupViews(){
//NAVIGATIONBAR:
//title
title = "Weather"
//set to hidden because on initial load there is a scroll view layered over top of the CityViewTableView (code not shown here). This gets set to false when the scrollView alpha is set to 0 and the CityViewTableView is revealed
navigationController?.navigationBar.isHidden = true
navigationController?.navigationBar.largeTitleTextAttributes = [.foregroundColor: UIColor.white]
//NAVIGATION ITEM:
navigationItem.searchController = searchVC
//UISEARCHBARCONTROLLER:
searchVC.searchResultsUpdater = self
}
}
//MARK: -CityViewController Functions
extension ViewController{
//setUp TableView
func setupCityViewTableView(){
cityTableView.translatesAutoresizingMaskIntoConstraints = false
//set tableView delegate and dataSource
cityTableView.delegate = self
cityTableView.dataSource = self
//background color
cityTableView.backgroundColor = .black
//separator color
cityTableView.separatorColor = .clear
//is transparent on initial load
cityTableView.alpha = 0
//set tag
cityTableView.tag = 1000
//hide scroll indicator
cityTableView.showsVerticalScrollIndicator = false
//register generic cell
cityTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cityCell")
//add subview
view.addSubview(cityTableView)
//Auto Layout
cityTableView.leadingAnchor
.constraint(equalTo: view.leadingAnchor,
constant: 20).isActive = true
cityTableView.topAnchor
.constraint(equalTo: view.topAnchor,
constant: 0).isActive = true
cityTableView.trailingAnchor
.constraint(equalTo: view.trailingAnchor,
constant: -20).isActive = true
cityTableView.bottomAnchor
.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor,
constant: 0).isActive = true
}
}
//MARK: -TableView Controller
extension ViewController: UITableViewDelegate,
UITableViewDataSource{
//number of rows
func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
if tableView.tag == 1000{
return 5
}
return self.models[tableView.tag].count
}
//cell for row
func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
//CityViewController
if tableView.tag == 1000{
let cell = tableView.dequeueReusableCell(withIdentifier:
"cityCell", for: indexPath)
cell.textLabel?.text = "Test"
cell.textLabel?.textAlignment = .center
cell.backgroundColor = .systemGray
cell.selectionStyle = .none
cell.layer.cornerRadius = 30
cell.layer.borderColor = UIColor.black.cgColor
cell.layer.borderWidth = 5
cell.layer.cornerCurve = .continuous
return cell
}
//WeatherViewController
//code here for scrollView tableViews
}
//Height for row
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if tableView.tag == 1000{
return view.frame.size.height/7
}
return view.frame.size.height/10
}
//Should Highlight Row
func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
if tableView.tag == 1000{
return true
}
return false
}
//Did select row
func tableView(_ tableView: UITableView, didSelectRowAt
indexPath: IndexPath) {
//calls function for segue to Weather Scroll View (not shown)
if tableView.tag == 1000{
segueToWeatherView(indexPath: indexPath)
}
}
}
EDIT 3: When I comment out another function it finally works, but I'm not sure exactly why, or how to fix it. This is the function in question, addSubViews()
//setup viewController
func addSubViews(){
//add weatherView as subView of ViewController
view.addSubview(weatherView)
//add subviews to weatherView
weatherView.addSubview(scrollView)
weatherView.addSubview(pageControl)
weatherView.addSubview(segueToCityViewButton)
weatherView.addSubview(segueToMapViewButton)
}
Specifically, it works when I comment out this line:
view.addSubview(weatherView)
Here is all the code concerning the setting up of the weatherView and all of its subViews:
//Any additional setup goes here
private func setupViews(){
//VIEWCONTROLLER:
//title
title = "Weather"
//Background color of view Controller
view.backgroundColor = .darkGray
//WEATHERVIEW:
//Background color of weather view Controller
weatherView.backgroundColor = .clear
//weatherView frame
weatherView.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height)
//SCROLLVIEW:
//background color of scroll view
scrollView.backgroundColor = .clear
//scrollView frame
scrollView.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height)
//changed
//PAGECONTROL:
//page control frame
pageControl.frame = CGRect(x: 0, y: view.frame.height-view.frame.size.height/14, width: view.frame.width, height: view.frame.size.height/14)
//TRANSITIONVIEW:
//TransitionView frame
transitionView.frame = CGRect(x: 20, y: 0, width: view.frame.size.width-40, height: view.frame.size.height)
//BUTTONS:
//segue to CityView
segueToCityViewButton.frame = CGRect(x: (weatherView.frame.width/5*4)-20, y: weatherView.frame.height-weatherView.frame.size.height/14, width: weatherView.frame.width/5, height: pageControl.frame.height)
//segue to MapView:
segueToMapViewButton.frame = CGRect(x: 20, y: weatherView.frame.height-weatherView.frame.size.height/14, width: weatherView.frame.width/5, height: pageControl.frame.height)
//LABELS:
transitionViewLabel.frame = transitionView.bounds
//NAVIGATIONBAR:
//set to hidden on initial load
navigationController?.navigationBar.isHidden = true
navigationController?.navigationBar.largeTitleTextAttributes = [.foregroundColor: UIColor.white]
//NAVIGATION ITEM:
navigationItem.searchController = searchVC
//UISEARCHBARCONTROLLER:
searchVC.searchResultsUpdater = self
}
For the sake of being thorough, here is the full viewDidLoad() Function:
override func viewDidLoad() {
super.viewDidLoad()
//MARK: View Controller
//These two will eventually be moved to the DispatchQueue in APICalls.swift
configureScrollView()
pageControl.numberOfPages = models.count
//Do any setup for the view controller here
setupViews()
//setup ViewController
addSubViews()
//Add Target for the pageControl
addTargetForPageControl()
//MARK: CityViewController
setupCityViewTableViews()
}
EDIT 4: With the following changes in viewDidLoad(), I finally got it to work!
override func viewDidLoad() {
super.viewDidLoad()
//MARK: CityViewController
//Moved to a position before setting up the other views
setupCityViewTableViews()
//MARK: View Controller
//These two will eventually be moved to the DispatchQueue in APICalls.swift
configureScrollView()
pageControl.numberOfPages = models.count
//Do any setup for the view controller here
setupViews()
//setup ViewController
addSubViews()
//Add Target for the pageControl
addTargetForPageControl()
}
Doing it the way you are doing it right now is a way to do it but I think it is the most challenging way to do it for several reasons:
You don't have much control and access to the implementation of the search controller animation within the navigation bar so getting the right coordinates might be a task
Even if you did manage to get the right coordinates, trying to synchronize your animation frames and timing to look in sync and seamless with the search animation on the nav bar will be tricky
I suggest the 2 following alternatives to what you are currently doing where you will get the news experience pretty much for free out of the box.
Option 1: Use a UITableViewController instead of a UIViewController
This is all the code using a UITableViewController and adding a UISearchController to the navigation bar.
class NewsTableViewVC: UITableViewController
{
private let searchController: UISearchController = {
let sc = UISearchController(searchResultsController: nil)
sc.obscuresBackgroundDuringPresentation = false
sc.searchBar.placeholder = "Search"
sc.searchBar.autocapitalizationType = .allCharacters
return sc
}()
override func viewDidLoad()
{
super.viewDidLoad()
view.backgroundColor = .black
title = "Weather"
// Ignore this as you have you own custom cell class
tableView.register(CustomCell.self,
forCellReuseIdentifier: CustomCell.identifier)
setUpNavigationBar()
}
private func setUpNavigationBar()
{
navigationItem.searchController = searchController
}
}
This is the experience you can expect
Option 2: Use auto layouts rather than frames to configure your UITableView
If you don't want to use a UITableViewController, configure your UITableView using auto layout rather than frames which has a little more work but not too much:
class NewsTableViewVC: UIViewController, UITableViewDataSource, UITableViewDelegate
{
private let searchController: UISearchController = {
let sc = UISearchController(searchResultsController: nil)
sc.obscuresBackgroundDuringPresentation = false
sc.searchBar.placeholder = "Search"
sc.searchBar.autocapitalizationType = .allCharacters
return sc
}()
private let tableView = UITableView()
override func viewDidLoad()
{
super.viewDidLoad()
// Just to show it's different from the first
view.backgroundColor = .purple
title = "Weather"
setUpNavigationBar()
setUpTableView()
}
private func setUpNavigationBar()
{
navigationItem.searchController = searchController
}
private func setUpTableView()
{
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.register(CustomCell.self,
forCellReuseIdentifier: CustomCell.identifier)
tableView.dataSource = self
tableView.delegate = self
tableView.backgroundColor = .clear
view.addSubview(tableView)
// Auto Layout
tableView.leadingAnchor
.constraint(equalTo: view.leadingAnchor,
constant: 0).isActive = true
// This important, configure it to the top of the view
// NOT the safe area margins to get the desired result
tableView.topAnchor
.constraint(equalTo: view.topAnchor,
constant: 0).isActive = true
tableView.trailingAnchor
.constraint(equalTo: view.trailingAnchor,
constant: 0).isActive = true
tableView.bottomAnchor
.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor,
constant: 0).isActive = true
}
}
You can expect the following experience:
Update
This is based on your updated code, you missed one small detail which might be impacting the results you see and this is the top constraint of the UITableView.
You added the constraint to the safeAreaLayoutGuide top anchor:
cityTableView.topAnchor
.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor,
constant: 0).isActive = true
My recommendation from the code above if you notice is to add it to the view top constraint
// This important, configure it to the top of the view
// NOT the safe area margins to get the desired result
cityTableView.topAnchor
.constraint(equalTo: view.topAnchor,
constant: 0).isActive = true
Give this a go and see if you come close to getting what you expect ?
Here is a link to the complete code of my implementation if it helps:

Thread 1 EXC_BAD_ACCESS when loading custom UIView from .xib file

I am trying to load a number of custom UIViews from a .xib file into a UIScrollView and I keep getting "Thread 1: EXC_BAD_ACCESS".
Since it's the first time when I'm actually trying to load a custom UIView (done this many times for UICollectionView and UITableView cells), I've been following this tutorial.
class PreSignupDataQuestionView : NibView
{
#IBOutlet weak var vMainContainer: UIView!
#IBOutlet weak var vQuestionViewContainer: UIView!
#IBOutlet weak var ivQuestionViewImage: UIImageView!
#IBOutlet weak var lblQuestion: UILabel!
}
class NibView : UIView
{
var view: UIView!
override init(frame: CGRect)
{
super.init(frame: frame)
xibSetup()
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
xibSetup()
}
}
private extension NibView
{
func xibSetup()
{
backgroundColor = UIColor.clear
view = loadNib()
view.frame = bounds
addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[childView]|",
options: [],
metrics: nil,
views: ["childView": view!]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[childView]|",
options: [],
metrics: nil,
views: ["childView": view!]))
}
}
extension UIView
{
func loadNib() -> UIView
{
let bundle = Bundle(for: type(of: self))
let nibName = type(of: self).description().components(separatedBy: ".").last!
let nib = UINib(nibName: nibName, bundle: bundle)
// Error pops here
return nib.instantiate(withOwner: self, options: nil).first as! UIView
}
}
Inside my UIViewController I have a function that sets up the UIScrollView and it works fine until I try to load the custom UIView.
for index in 0..<self.screenData.count
{
let xCoordinate = (CGFloat(index) * (width)) + firstSpace
let viewFrame = CGRect(x: xCoordinate, y: 0, width: width - spaceBetweenView, height: height)
let childView = PreSignupDataQuestionView().loadNib() as! PreSignupDataQuestionView
childView.frame = viewFrame
childView.tag = index
childView.isUserInteractionEnabled = true
childView.ivQuestionViewImage.image = UIImage(named: "PlaceholderImage")
childView.lblQuestion.text = "Lorep Ipsum"
self.svQuestions.addSubview(childView)
}
However, I have no problem loading a UIView if there is no .xib involved:
let xCoordinate = (CGFloat(index) * (width)) + firstSpace + lastSpace
let viewFrame = CGRect(x: xCoordinate, y: 0, width: width - spaceBetweenView, height: height)
let childView = UIView()
childView.tag = index
childView.isUserInteractionEnabled = true
if index % 2 == 0 { childView.backgroundColor = .red }
else { childView.backgroundColor = .green }
childView.frame = viewFrame
self.scrollView.addSubview(childView)
Any ideas? I've been trying to load a custom UIView into a UIScrollView for some time now and can't seem to figure this out.
I know this is a common issue but so far nothing worked for me.
That tutorial isn't quite right...
When loading the custom view - your PreSignupDataQuestionView - via code, change this line:
let childView = PreSignupDataQuestionView().loadNib() as! PreSignupDataQuestionView
to simply:
let childView = PreSignupDataQuestionView()
That should take care of it.
EDIT:
Try this in a new view controller, to rule out any other possible issues:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let childView = PreSignupDataQuestionView()
childView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(childView)
NSLayoutConstraint.activate([
childView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 100),
childView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 50),
childView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -50),
childView.heightAnchor.constraint(equalToConstant: 300),
])
}
}
EDIT 2:
I posted a complete sample project at https://github.com/DonMag/XIBLoadExtension
See if that works for you. If so, then compare to what you've got to see what's different.

Set initial ScrollView

I want to set "ViewController2" as initial page in the ScrollView but changing setContentOffset(CGPointMake(0,0), animated: false) sets the first page as initial, i tried modified it with different numbers but it just messed up the pages, any tips?
import UIKit
class ViewController: UIViewController {
#IBOutlet var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
scrollView.bounces = false
scrollView.pagingEnabled = true
scrollView.setContentOffset(CGPointMake(0,0), animated: false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewDidLayoutSubviews() {
initScrollView()
}
func initScrollView(){
let viewController1 = storyboard?.instantiateViewControllerWithIdentifier("ViewController1") as! ViewController1
viewController1.willMoveToParentViewController(self)
viewController1.view.frame = scrollView.bounds
let viewController2 = storyboard?.instantiateViewControllerWithIdentifier("ViewController2") as! ViewController2
viewController2.willMoveToParentViewController(self)
viewController2.view.frame.size = scrollView.frame.size
viewController2.view.frame.origin = CGPoint(x: view.frame.width, y: 0)
let viewController3 = storyboard?.instantiateViewControllerWithIdentifier("ViewController3") as! ViewController3
viewController3.willMoveToParentViewController(self)
viewController3.view.frame.size = scrollView.frame.size
viewController3.view.frame.origin = CGPoint(x: view.frame.width * 2, y: 0)
scrollView.contentSize = CGSize(width: 3 * scrollView.frame.width, height: scrollView.frame.height)
scrollView.addSubview(viewController3.view)
self.addChildViewController(viewController3)
viewController3.didMoveToParentViewController(self)
scrollView.addSubview(viewController2.view)
self.addChildViewController(viewController2)
viewController2.didMoveToParentViewController(self)
scrollView.addSubview(viewController1.view)
self.addChildViewController(viewController1)
viewController1.didMoveToParentViewController(self)
}}
Try to de-select the scroll view inset adjustment... in vc2:
By putting scrollView.setContentOffset(CGPointMake(375,0), animated: false) in viewDidlayoutSubViews it loads the next view, note that i am using iphone 4,7 inch screen so the width of a viewController is 375. change 375 to the width of your viewController, for example if you wanna load the last page first you do add 375 to 375 and so on..
override func viewDidLayoutSubviews() {
initScrollView()
scrollView.setContentOffset(CGPointMake(375,0), animated: false)
}

View does not animate

I have a view, which shall move up like a drawer from the bottom of the screen. But it does not do anything. It just sits there =)
Can anyone please tell me, why it is doing that?
This is my code:
import UIKit
class InfoPopUpVC: UIViewController {
var superView: UIView!
var labelText: String!
let textLabel = UILabel()
let height = CGFloat(80)
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
UIView.animateWithDuration(0.4, animations: { () -> Void in
self.view.center.y = 50
})
}
override func viewDidLoad() {
super.viewDidLoad()
setupTextLabel()
view.frame = CGRectMake(0, superView.frame.maxY-height, superView.frame.width, height)
AnimationHelper.blurBackgroundForView(view)
view.backgroundColor = .greenColor()
}
func setupTextLabel(){
textLabel.text = labelText
textLabel.frame = CGRectMake(0, 0, view.frame.width, view.frame.height)
textLabel.numberOfLines = 3
textLabel.textAlignment = .Center
textLabel.frame.inset(dx: 10, dy: 8)
textLabel.sizeToFit()
textLabel.font = UIFont(name: "HelveticaNeue-Light", size: 17)
textLabel.textColor = .whiteColor()
view.addSubview(textLabel)
}
}
Try to put your code as follow inside viewDidAppear or viewWillAppear and with dispatch async. Otherwise your animation might not work.
override func viewDidAppear(animated: Bool) {
dispatch_async(dispatch_get_main_queue(), {
UIView.animateWithDuration(0.4, animations: { () -> Void in
self.view.center.y = 50
})
})
}
You cannot animate a frame or similar property, if the UIViewis constrained using autolayout.
You have two options:
Get rid of autolayout and animate the frames Directory
Use autolayout and animate the constraints (e.g. via outlets)
See the following links for examples:
How do I animate constraint-changes
IOS: ANIMATING AUTOLAYOUT CONSTRAINTS