ios - 所选元素下方带有条形的分段控件
问题描述
我正在尝试在选定的段控件下方创建条形效果。我正在创建一个附加到底部并根据所选元素移动的 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)
}
}
}
解决方案
推荐阅读
- php - 从 PHP 7.1 更新到 7.3 和错误 one.com
- javascript - 如何“优先考虑”香草 javascript if 语句?
- java - 为什么 Keycloak 安全约束在 @SpringBootTest 中未激活,我该如何激活它们?
- jquery - 如何从 Jodit 文本编辑器中获取内容
- php - 如何使用 php 从谷歌驱动器文件中获取下载 url?
- arduino - 在 uart 中接收整个字符串发送数据
- html - 如何在 behat 3.5 中运行 behat-html-formatter
- r - 反向距离加权:spDists(s0, s) 中的错误:ncol(x) == ncol(y) 在包 gstat 中不是 TRUE
- c - 为什么我能够在这个 char 数组中存储比使用 malloc() 提供的更多的字节?
- android - 错误:标签“action”的强制属性“id”缺失