我正在尝试在选定的细分控件下方创建条形效果。我正在创建一个UIView,该UIView附加到底部并根据所选元素而移动。但是,有一个错误会导致该栏在您第一次点击时回到第一个元素。
我尝试过使用自动布局和框架
@IBOutlet weak var segmentControl: UISegmentedControl!
fileprivate var buttonBar = UIView()
//viewDidLoad
buttonBar = UIView()
self.view.insertSubview(buttonBar, aboveSubview: segmentControl)
// This needs to be false since we are using auto layout constraints
buttonBar.translatesAutoresizingMaskIntoConstraints = false
buttonBar.backgroundColor = UIColor.white
buttonBar.topAnchor.constraint(equalTo: segmentControl.bottomAnchor).isActive = true
buttonBar.heightAnchor.constraint(equalToConstant: 2).isActive = true
// Constrain the button bar to the left side of the segmented control
buttonBar.leftAnchor.constraint(equalTo: segmentControl.leftAnchor).isActive = true
// Constrain the button bar to the width of the segmented control divided by the number of segments
buttonBar.widthAnchor.constraint(equalTo: segmentControl.widthAnchor, multiplier: 1 / CGFloat(segmentControl.numberOfSegments)).isActive = true
@objc func segmentedControlValueChanged(_ sender: UISegmentedControl) {
showSearchResults()
DispatchQueue.main.async {
UIView.animate(withDuration: 0.3) {
let segmentSize = (self.segmentControl.frame.width / CGFloat(self.segmentControl.numberOfSegments))
let segmentOrigin = self.segmentControl.frame.origin.x
let index = CGFloat(self.segmentControl.selectedSegmentIndex)
self.buttonBar.frame.origin.x = segmentOrigin + (segmentSize * index)
}
}
}