Volkan Elçi Volkan Elçi - 10 months ago 50
Swift Question

Swift - Horizontal Bar under selected button

I want to add a white horizontal bar under my selected button on the menu. Just like YouTube app. This is my menu

Abd this is Youtube

I searched for info but i couldnt find anything about this. And this is my code. Thanks

import UIKit

class TabViewController: UIViewController {

@IBOutlet var contentView: UIView!
@IBOutlet var buttons: [UIButton]!

var rifleViewController: UIViewController!
var pistolViewController: UIViewController!
var shotgunViewController: UIViewController!
var smgsViewController: UIViewController!
var sniperViewController: UIViewController!

var viewControllers: [UIViewController]!
var selectedIndex: Int = 0

override func viewDidLoad() {

let storyboard = UIStoryboard(name: "Main", bundle: nil)

rifleViewController = storyboard.instantiateViewController(withIdentifier: "rifles")
sniperViewController = storyboard.instantiateViewController(withIdentifier: "snipers")
smgsViewController = storyboard.instantiateViewController(withIdentifier: "smgss")
shotgunViewController = storyboard.instantiateViewController(withIdentifier: "shotguns")
pistolViewController = storyboard.instantiateViewController(withIdentifier: "pistols")
viewControllers = [rifleViewController,

buttons[selectedIndex].isSelected = true


override func didReceiveMemoryWarning() {
// Dispose of any resources that can be recreated.

@IBAction func didPressTab(_ sender: UIButton) {

let previousIndex = selectedIndex

selectedIndex = sender.tag

buttons[previousIndex].isSelected = false
let previousVC = viewControllers[previousIndex]

previousVC.willMove(toParentViewController: nil)

sender.isSelected = true

let vc = viewControllers[selectedIndex]


vc.view.frame = contentView.bounds
vc.didMove(toParentViewController: self)



Answer Source

You could achieve this with the help of a simple animation. In my example - App, I added a view at the top of the screen in the storyboard and put four buttons on top of it. Then i connected the buttons to the function called "buttonTapped" (important: you need to include the sender here). The code is fairly simple:

class ViewController: UIViewController {

@IBOutlet weak var backgroundView: UIView!
var movingView = UIView()

override func viewDidLoad() {

    let screenWidth = UIScreen.main.bounds.width

    movingView = UIView(frame: CGRect(x: 0, y: 55, width: screenWidth / 4, height: 5))
    movingView.backgroundColor = UIColor.white   //if backgroundView's color is black

@IBAction func buttonTapped(_ sender: UIButton)
    let newx = sender.frame.origin.x

    UIView.animate(withDuration: 1) {
        self.movingView.frame.origin.x = newx