首页 > 解决方案 > 所选元素下方带有条形的分段控件

问题描述

我正在尝试在选定的段控件下方创建条形效果。我正在创建一个附加到底部并根据所选元素移动的 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)
    }
  }
}

标签: iosswiftuisegmentedcontrol

解决方案


推荐阅读