swipe between UIView with segemented control programmatically - swift

hi fellow developer I want to swipe between uiview with scrollView while changing the the index and small indicator move left and right. but is not responding while I try to swipe. this is my picture and my setup to scroll between uiview. can you tell me where I am missing?
let segmentedControl = UISegmentedControl()
let containerView = UIView()
let indicatorView = UIView()
let leftView = UIView()
let rightView = UIView()
let scrollView = UIScrollView()
var slides = [UIView]()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
slides.append(leftView)
slides.append(rightView)
segmentedControl.insertSegment(withTitle: "Harian", at: 0, animated: true)
segmentedControl.insertSegment(withTitle: "Mata Pelajaran", at: 1, animated: true)
segmentedControl.selectedSegmentIndex = 0
segmentedControl.addTarget(self, action: #selector(handleTap), for: .valueChanged)
setupSlideScrollView()
}
func setupSlideScrollView() {
view.addSubview(scrollView)
scrollView.isPagingEnabled = true
scrollView.translatesAutoresizingMaskIntoConstraints = false
for i in 0..<slides.count {
slides[i].frame = CGRect(x: view.frame.width * CGFloat(i), y: 0, width: view.frame.width, height: view.frame.height)
scrollView.addSubview(slides[i])
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let pageIndex = round(scrollView.contentOffset.x / view.frame.width)
segmentedControl.selectedSegmentIndex = Int(pageIndex)
}
#objc func handleTap(_ sender: UISegmentedControl) {
indicatorView.frame.origin.x = (segmentedControl.frame.width / CGFloat(segmentedControl.numberOfSegments)) * CGFloat(segmentedControl.selectedSegmentIndex)
UIView.animate(withDuration: 0.5, animations: {
self.view.layoutIfNeeded()
self.indicatorView.transform = CGAffineTransform(scaleX: 0.7, y: 1)
}) { (finish) in
UIView.animate(withDuration: 0.4, animations: {
self.indicatorView.transform = CGAffineTransform.identity
})
}
}

Related

Animate UILabel from a location to another location in the save UIViewController

I have 2 UILabels: usernameLabel located in left top corner and fadingWelcomeMessageLabel where I show a welcome message to user.
I want to implement a simple animation with a custom duration of few seconds which will minimise the size and fade (disolve) my fadingWelcomeMessageLabel from is original position to usernameLabel position.
How will be this possible ?
Below is a screenshot with what I want to do and also my current source code.
Thanks in advance.
import UIKit
class ViewController: UIViewController {
var fadingWelcomeMessageLabel: UILabel!
var usernameLabel : UILabel!
override func viewDidLoad() {
super.viewDidLoad()
setupUsernameLabel()
setupWelcomeMessageLabel()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UILabel.transition(with: usernameLabel, duration: 0.5, options: UIView.AnimationOptions.transitionCrossDissolve, animations: {
}, completion: { (fininshed: Bool) -> () in
self.fadeWelcomeMessage(message: "Hello, Mr User !", color: .orange, finalAlpha: 0.0)
})
}
func setupUsernameLabel() {
usernameLabel = UILabel()
usernameLabel.text = "Mr User"
usernameLabel.numberOfLines = 0
view.addSubview(usernameLabel)
usernameLabel.translatesAutoresizingMaskIntoConstraints = false
usernameLabel.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor, constant: 10).isActive = true
usernameLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
usernameLabel.widthAnchor.constraint (equalToConstant: 200).isActive = true
usernameLabel.heightAnchor.constraint (equalToConstant: 50).isActive = true
}
func setupWelcomeMessageLabel() {
// Fading Welcome Message Label
fadingWelcomeMessageLabel = UILabel()
fadingWelcomeMessageLabel.text = String()
fadingWelcomeMessageLabel.numberOfLines = 0
view.addSubview(fadingWelcomeMessageLabel)
fadingWelcomeMessageLabel.isHidden = true
fadingWelcomeMessageLabel.translatesAutoresizingMaskIntoConstraints = false
fadingWelcomeMessageLabel.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor).isActive = true
fadingWelcomeMessageLabel.topAnchor.constraint (equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
fadingWelcomeMessageLabel.widthAnchor.constraint (equalTo: view.safeAreaLayoutGuide.widthAnchor).isActive = true
fadingWelcomeMessageLabel.heightAnchor.constraint (equalToConstant: 200).isActive = true
}
func fadeWelcomeMessage(message: String, color: UIColor, finalAlpha: CGFloat) {
fadingWelcomeMessageLabel.text = message
fadingWelcomeMessageLabel.alpha = 1.0
fadingWelcomeMessageLabel.isHidden = false
fadingWelcomeMessageLabel.textAlignment = .center
fadingWelcomeMessageLabel.backgroundColor = color
fadingWelcomeMessageLabel.layer.cornerRadius = 5
fadingWelcomeMessageLabel.layer.masksToBounds = true
fadingWelcomeMessageLabel.font = UIFont.systemFont(ofSize: 24.0)
UIView.animate(withDuration: 6.0, animations: { () -> Void in
self.fadingWelcomeMessageLabel.alpha = finalAlpha
})
}
}
CGAffineTransform can help you. You can run my code and change value according to your needs. I have showed only for fadingWelcomeMessageLabel. Hope you will get the idea.
class ViewController: UIViewController {
let fadingWelcomeMessageLabel = UILabel()
let usernameLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .gray
viewSetup()
}
override func viewDidAppear(_ animated: Bool) {
DispatchQueue.main.asyncAfter(deadline: .now()+3, execute: {
UIView.animate(withDuration: 1.5) {
self.fadingWelcomeMessageLabel.transform = CGAffineTransform(translationX: -300, y: -2200).concatenating(CGAffineTransform(scaleX: 0.4, y: 0.2))
}
})
}
func viewSetup() {
fadingWelcomeMessageLabel.frame = CGRect(x: 10, y: view.frame.height/2 - 50, width: view.frame.width - 20, height: 300)
fadingWelcomeMessageLabel.text = "Welcome Mr. David"
fadingWelcomeMessageLabel.textColor = .green
fadingWelcomeMessageLabel.textAlignment = .center
fadingWelcomeMessageLabel.backgroundColor = .red
view.addSubview(fadingWelcomeMessageLabel)
}
}
Solution for my issue was resolved with 1 line of code inside animation closure:
func fadeWelcomeMessage(message: String, color: UIColor, finalAlpha: CGFloat) {
fadingWelcomeMessageLabel.text = message
fadingWelcomeMessageLabel.alpha = 1.0
fadingWelcomeMessageLabel.isHidden = false
fadingWelcomeMessageLabel.textAlignment = .center
fadingWelcomeMessageLabel.backgroundColor = color
fadingWelcomeMessageLabel.layer.cornerRadius = 5
fadingWelcomeMessageLabel.layer.masksToBounds = true
fadingWelcomeMessageLabel.font = UIFont.systemFont(ofSize: 24.0)
UIView.animate(withDuration: 6.0, delay: 4.0, animations: { () -> Void in
self.fadingWelcomeMessageLabel.transform = CGAffineTransform(translationX: -180, y: -80).scaledBy(x: 0.20, y: 0.20)
self.fadingWelcomeMessageLabel.alpha = finalAlpha
}) { finish in
self.setupWelcomeMessageLabel()
}
}
Output:

UIScrollView with paging enable not working properly

Trying to add four UIView's in UIScrollView
The issue is next (2, 3, and 4) view gets a bit off from the visible screen view when scroll.
override init(frame: CGRect) {
super.init(frame: frame)
configureSlider()
}
private func configureSlider() {
Bundle.main.loadNibNamed("CarouselSliderView", owner: self, options: nil)
addSubview(contentView)
for i in 0...3 {
let view = UIView()
switch i {
case 0:
view.backgroundColor = .brown
case 1:
view.backgroundColor = .yellow
case 2:
view.backgroundColor = .green
case 3:
view.backgroundColor = .blue
default:
view.backgroundColor = .red
}
slides.append(view)
}
setupSlideScrollView(slides: slides)
pageControl.numberOfPages = slides.count
pageControl.currentPage = 0
self.bringSubviewToFront(pageControl)
}
set each UIView frames:
private func setupSlideScrollView(slides : [UIView]) {
let screenRect = UIScreen.main.bounds
let screenWidth = screenRect.size.width
for i in 0 ..< slides.count {
slides[i].frame = CGRect(x: screenWidth * CGFloat(i), y: 0, width: screenWidth, height: self.frame.height)
topScrollView.addSubview(slides[i])
}
topScrollView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: self.frame.height)
topScrollView.contentSize = CGSize(width: screenWidth * CGFloat(slides.count), height: self.frame.height)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let pageIndex = round(scrollView.contentOffset.x/self.frame.width)
pageControl.currentPage = Int(pageIndex)
}

textField will not move in programable scrollview

I have a UIScrollView. I have a UITextField and a UILabel. For some reason my UITextField it will not move in my scroll view but my UILablel will. I have added the UITextField the same way as I added my UILabel to the scrollview using scrollView.addSubview(textField). Anyone see what I am doing wrong on this one?
import Foundation
import UIKit
//here
protocol AddContactDelegate {
func addContact(contact: Contact)
}
class AddContactController: UIViewController {
//delegate
var delegate: AddContactDelegate?
//TextField
let textField: UITextField = {
let tf = UITextField()
tf.placeholder = "Add Your Workout Title"
tf.textAlignment = .center
tf.translatesAutoresizingMaskIntoConstraints = false
return tf
}()
override func viewDidLoad() {
super.viewDidLoad()
//making scroll view
let screensize: CGRect = UIScreen.main.bounds
let screenWidth = screensize.width
let screenHeight = screensize.height
var scrollView: UIScrollView!
scrollView = UIScrollView(frame: CGRect(x: 0, y: 120, width: screenWidth, height: screenHeight))
scrollView.contentSize = CGSize(width: screenWidth, height: 2000)
view.addSubview(scrollView)
//setting up how view looks-----
view.backgroundColor = .white
//top buttons
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(handleDone))
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(handleCancel))
//view elements
view.addSubview(textField)
scrollView.addSubview(textField)
textField.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
textField.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
textField.widthAnchor.constraint(equalToConstant: view.frame.width - 64).isActive = true
textField.becomeFirstResponder()
//excercise label
let excerciseNumber = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
excerciseNumber.center = CGPoint(x: view.frame.width / 2 , y: view.frame.height / 20)
excerciseNumber.textAlignment = .center
excerciseNumber.text = "Workout Title"
self.view.addSubview(excerciseNumber)
scrollView.addSubview(excerciseNumber)
}
//done button
#objc func handleDone(){
print("done")
guard let fullname = textField.text, textField.hasText else {
print("handle error here")
return
}
let contact = Contact(fullname: fullname, hello: "hi")
delegate?.addContact(contact: contact)
print(contact.fullname)
print(contact.hello)
}
//cancel button
#objc func handleCancel(){
self.dismiss(animated: true, completion: nil )
}
}
As you make the center x and y of the textfield with view not scrollView , You need
textField.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
textField.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor),
textField.centerYAnchor.constraint(equalTo: scrollView.centerYAnchor),
textField.widthAnchor.constraint(equalToConstant: view.frame.width - 64)
])
Also remove
view.addSubview(textField)
self.view.addSubview(excerciseNumber)

Adding a search bar to ui table view on overlay

I have managed to create, a dark overlay once clicked a search icon and have managed to add a table uiview on the dark overlay but now want to add a search bar within that table view. I cant seem to figure it out as my code seems different to everyone else's examples. I am new to swift so my code probably isn't the cleanest. can i ask if someone can show me how to do this as i am out of ideas. I have posted my code below can someone please show me where i'm going wrong.
Many thanks
class SearchLauncher: NSObject {
let blackView = UIView()
let tableView = UITableView()
#objc func showSearch() {
if let window = UIApplication.shared.keyWindow {
blackView.backgroundColor = UIColor(white: 0, alpha: 0.5)
blackView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleDismiss)))
window.addSubview(blackView)
window.addSubview(tableView)
let height: CGFloat = 600
let y = window.frame.height - height
tableView.frame = CGRect(x: 0, y: window.frame.height, width: window.frame.width, height: height)
blackView.frame = window.frame
blackView.alpha = 0
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
self.blackView.alpha = 1
self.tableView.frame = CGRect(x: 0, y: y, width: self.tableView.frame.width, height: self.tableView.frame.height)
}, completion: nil)
}
}
#objc func handleDismiss() {
UIView.animate(withDuration: 0.5) {
self.blackView.alpha = 0
if let window = UIApplication.shared.keyWindow {
self.tableView.frame = CGRect(x: 0, y: window.frame.height, width: self.tableView.frame.width, height: self.tableView.frame.height)
}
}
}
override init() {
super.init()
//start doing something here maybe
}
}```
How did you try to add a search controller?
I would do it by adding an UISearchController as a tableHeaderView of your table view. First make sure to add UISearchResultsUpdating protocol to your class.
class SearchLauncher: NSObject, UISearchResultsUpdating
Then add the search bar to your table view
let searchController = UISearchController(searchResultsController: nil)
searchController.searchBar.sizeToFit()
searchController.searchResultsUpdater = self
//you probably don't need this
//searchController.dimsBackgroundDuringPresentation = false
tableView.tableHeaderView = searchController.searchBar
And then, implement the updateSearchResults(for:_) delegate method
func updateSearchResults(for searchController: UISearchController) {
filteredTableData.removeAll(keepingCapacity: false)
//filter the table data by using searchController.searchBar.text!
//filteredTableData = ...
self.tableView.reloadData()
}

UISwipeGestureRecognizer not recognized when added to UIView's subviews

I currently have a subclass of UIView which contains numerous subviews. I wish to add a UISwipeGesture to the subviews but unfortunately the swipe gesture is not recognized. I've set userInteractionEnabled = true and direction of the swipe gesture but nothing works.
public class CardStackView: UIView{
public var dataSource = [UIImage]()
private var swipeGuesture: UISwipeGestureRecognizer!
override public func layoutSubviews() {
for img in dataSource{
let view = AppView(image: img, frame: self.frame)
self.addSubview(view)
}
animateSubview()
self.userInteractionEnabled = true
}
func animateSubview(){
for (index, sView) in self.subviews.enumerate() {
swipeGuesture = UISwipeGestureRecognizer(target: self, action: #selector(self.swipeGuestureDidSwipeRight(_:)))
swipeGuesture.direction = .Right
sView.addGestureRecognizer(swipeGuesture)
sView.userInteractionEnabled = true
let move: CGFloat = CGFloat(-20 + index * 20)
let opacity = Float(1 - 0.2 * CGFloat(index))
sView.shadowOpacity(opacity).shadowOffset(CGSizeMake(20 - CGFloat(index) * 5, 20 - CGFloat(index) * 5)).shadowRadius(5).moveX(-move).moveY(-move).gravity().shadowColor(UIColor.grayColor()).duration(1)
.completion({
}).animate()
}
}
func swipeGuestureDidSwipeRight(gesture: UISwipeGestureRecognizer) {
print("Swiped right")
let subview = self.subviews[0]
subview.moveX(-60).duration(1).animate()
}
}
Example
class ExampleController: UIViewController {
var stackView: CardStackView!
override func viewDidLoad() {
super.viewDidLoad()
stackView = CardStackView(frame: CGRect(x: 20, y: 80, width: 200, height: 200))
stackView.dataSource = [UIImage(named: "2008")!, UIImage(named: "2008")!]
self.view.addSubview(stackView)
}
}
self.view.bringSubviewToFront(yourSubview)
try this code for all your subviews and if it doesn't work try this in your controller class for your CardStackView.
Try to call setNeedsLayout for stackView:
override func viewDidLoad() {
super.viewDidLoad()
stackView = CardStackView(frame: CGRect(x: 20, y: 80, width: 200, height: 200))
stackView.dataSource = [UIImage(named: "2008")!, UIImage(named: "2008")!]
stackView.setNeedsLayout()
self.view.addSubview(stackView)
}