我想在菜单上的所选按钮下添加一个白色水平条。就像YouTube应用。 This is my menu
我搜索了信息,但我找不到任何相关信息。这是我的代码。感谢
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() {
super.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,
pistolViewController,
shotgunViewController,
smgsViewController,
sniperViewController]
buttons[selectedIndex].isSelected = true
didPressTab(buttons[selectedIndex])
}
override func didReceiveMemoryWarning() {
super.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)
previousVC.view.removeFromSuperview()
previousVC.removeFromParentViewController()
sender.isSelected = true
let vc = viewControllers[selectedIndex]
addChildViewController(vc)
vc.view.frame = contentView.bounds
contentView.addSubview(vc.view)
vc.didMove(toParentViewController: self)
}
}
答案 0 :(得分:0)
您可以借助简单的动画实现这一目标。 在我的示例 - 应用程序中,我在故事板的屏幕顶部添加了一个视图,并在其顶部放置了四个按钮。然后我将按钮连接到名为“buttonTapped”的功能(重要的是:您需要在此处包含发件人)。 代码很简单:
class ViewController: UIViewController {
@IBOutlet weak var backgroundView: UIView!
var movingView = UIView()
override func viewDidLoad() {
super.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
backgroundView.addSubview(movingView)
}
@IBAction func buttonTapped(_ sender: UIButton)
{
let newx = sender.frame.origin.x
UIView.animate(withDuration: 1) {
self.movingView.frame.origin.x = newx
}
}
}