Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // CustomSegmentedControl.swift
- // SuperBoss
- //
- // Created by STENIO FREITAS on 19/08/17.
- // Copyright © 2017 Stenio Wagner. All rights reserved.
- //
- import UIKit
- class CustomSegmentedControl: UIControl {
- var selectorTextColor: UIColor = .white
- var selectorColor: UIColor = .darkGray
- var selector: UIView!
- var borderColor: UIColor = .yellow
- var borderWidth: CGFloat = 1
- var textColor: UIColor = .lightGray
- let buttonTitles = ["Podcasts", "Vídeos"]
- var buttons = [UIButton]()
- override func draw(_ rect: CGRect) {
- layer.cornerRadius = frame.height / 2
- }
- func updateViews() {
- subviews.forEach { $0.removeFromSuperview() }
- buttons.removeAll()
- setupButtons(buttonTitles)
- buttons[0].setTitleColor(selectorTextColor, for: .normal)
- setupSelector(numberOfTitles: buttonTitles.count)
- setupStackView()
- }
- func setupButtons(_ buttonTitles: [String]) {
- for buttonTitle in buttonTitles {
- let button = UIButton(type: .system)
- button.setTitle(buttonTitle, for: .normal)
- button.setTitleColor(textColor, for: .normal)
- button.addTarget(self, action: #selector(onSegmentedControlChanged(buttonClicked:)), for: .touchUpInside)
- buttons.append(button)
- }
- }
- func setupSelector(numberOfTitles: Int) {
- let selectorWidth = frame.width / CGFloat(numberOfTitles)
- selector = UIView(frame: CGRect(x: 0, y: 0, width: Int(selectorWidth), height: Int(frame.height)))
- selector.layer.cornerRadius = frame.height / 2
- selector.backgroundColor = selectorColor
- addSubview(selector)
- }
- func setupStackView() {
- let stackView = UIStackView(arrangedSubviews: buttons)
- stackView.axis = .horizontal
- stackView.alignment = .fill
- stackView.distribution = .fillProportionally
- addSubview(stackView)
- stackView.translatesAutoresizingMaskIntoConstraints = false
- stackView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
- stackView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
- stackView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
- stackView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
- }
- func onSegmentedControlChanged(buttonClicked: UIButton) {
- for (buttonIndex, button) in buttons.enumerated() {
- button.setTitleColor(textColor, for: .normal)
- if button == buttonClicked {
- animateSegmentedControlChange(buttonTargetIndex: buttonIndex)
- button.setTitleColor(selectorTextColor, for: .normal)
- }
- }
- }
- func animateSegmentedControlChange(buttonTargetIndex: Int) {
- let selectorStartPosition = frame.width / CGFloat(buttons.count) * CGFloat(buttonTargetIndex)
- UIView.animate(withDuration: 0.3, animations: {
- self.selector.frame.origin.x = selectorStartPosition
- })
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement