I have design Animating the Button Bar UISegmentedControl "showUsers" in Swift and when I tried to implement the animation is not working the bar still hold the first Segment and not moving to the second segment example https://www.codementor.io/kevinfarst/designing-a-button-bar-style-uisegmentedcontrol-in-swift-cg6cf0dok
override public func viewDidLoad(){
super.viewDidLoad()
showUsers.backgroundColor = .clear
showUsers.tintColor = .clear
showUsers.setTitleTextAttributes([
NSAttributedString.Key.font : UIFont(name: "DINCondensed-Bold", size: 18),
NSAttributedString.Key.foregroundColor: UIColor(red:0.44, green:0.44, blue:0.44, alpha:1.0)
], for: .normal)
showUsers.setTitleTextAttributes([
NSAttributedString.Key.font : UIFont(name: "DINCondensed-Bold", size: 18),
NSAttributedString.Key.foregroundColor: UIColor(red:0.44, green:0.44, blue:0.44, alpha:1.0)
], for: .selected)
let buttonBar = UIView()
// This needs to be false since we are using auto layout constraints
buttonBar.translatesAutoresizingMaskIntoConstraints = false
buttonBar.backgroundColor = UIColor(red:0.44, green:0.44, blue:0.44, alpha:1.0)
view.addSubview(showUsers)
view.addSubview(buttonBar)
// Constrain the top of the button bar to the bottom of the segmented control
buttonBar.topAnchor.constraint(equalTo: showUsers.bottomAnchor).isActive = true
buttonBar.heightAnchor.constraint(equalToConstant: 5).isActive = true
// Constrain the button bar to the left side of the segmented control
buttonBar.leftAnchor.constraint(equalTo: showUsers.leftAnchor).isActive = true
// Constrain the button bar to the width of the segmented control divided by the number of segments
buttonBar.widthAnchor.constraint(equalTo: showUsers.widthAnchor, multiplier: 1 / CGFloat(showUsers.numberOfSegments)).isActive = true
showUsers.addTarget(self, action: #selector(HomeViewController.segmentedControlValueChanged(_:)), for: UIControl.Event.valueChanged)
}
@objc func segmentedControlValueChanged(_ sender: UISegmentedControl) {
UIView.animate(withDuration: 0.3) {
print(self.showUsers.frame.width) //147.0
print(self.showUsers.numberOfSegments) //2
print(self.showUsers.selectedSegmentIndex)//1
//let originX = (self.showUsers.frame.width / CGFloat(self.showUsers.numberOfSegments)) * CGFloat(self.showUsers.selectedSegmentIndex + 1)
let originX = (self.showUsers.frame.width / CGFloat(self.showUsers.numberOfSegments)) * CGFloat(self.showUsers.selectedSegmentIndex + 1)
self.buttonBar.frame.origin.x = originX
}
}
Update:
update the calculation function and it moves the line but not where I want
Your issue is that you are applying 'frame' changes on the view that has constraints, so try to use constraints in the method segmentedControlValueChanged
instead of this
let originX = (self.showUsers.frame.width / CGFloat(self.showUsers.numberOfSegments)) * CGFloat(self.showUsers.selectedSegmentIndex + 1)
self.buttonBar.frame.origin.x = originX