我有一个分段控件,如图所示有 4 个分段。
敌人,例如:有线线路、可管理的移动性
我想在选择任何段时在底部(发际线)获得红色;基本上它应该在选定的段显示红线
我现在的代码如下
func changeColor(sender: UISegmentedControl){
if sender.selectedSegmentIndex == 0 {
UIView.animateWithDuration(0.5, animations: {
self.containerAccountSummary.alpha = 1
self.containerLocationTracker.alpha = 0
self.containerWireline.alpha = 0
self.containerManagedMobility.alpha = 0
self.containerMobileVoiceAndData.alpha = 0
})
} else if sender.selectedSegmentIndex == 1{
UIView.animateWithDuration(0.5, animations: {
self.containerAccountSummary.alpha = 0
self.containerLocationTracker.alpha = 1
self.containerWireline.alpha = 0
self.containerManagedMobility.alpha = 0
self.containerMobileVoiceAndData.alpha = 0
})
}else if sender.selectedSegmentIndex == 2{
UIView.animateWithDuration(0.5, animations: {
self.containerAccountSummary.alpha = 0
self.containerLocationTracker.alpha = 0
self.containerWireline.alpha = 1
self.containerManagedMobility.alpha = 0
self.containerMobileVoiceAndData.alpha = 0
})
}else if sender.selectedSegmentIndex == 3{
UIView.animateWithDuration(0.5, animations: {
self.containerAccountSummary.alpha = 0
self.containerLocationTracker.alpha = 0
self.containerWireline.alpha = 0
self.containerManagedMobility.alpha = 1
self.containerMobileVoiceAndData.alpha = 0
})
}else {
UIView.animateWithDuration(0.5, animations: {
self.containerAccountSummary.alpha = 0
self.containerLocationTracker.alpha = 0
self.containerWireline.alpha = 0
self.containerManagedMobility.alpha = 0
self.containerMobileVoiceAndData.alpha = 1
})
}
}
有什么建议吗?
最佳答案
您可以将 UIView 用作细线并将其放置在 Storyboard上的分段控件下方。指定它的颜色和高度。将其宽度设置为等于分段控件中的单个分段,然后在调用分段控件操作时,采用选定的分段索引并根据该索引,通过提供 X 位置、Y 位置、高度和宽度来更改 UIView 的框架。然后将此框架设置为您的细线并在细线上调用方法 layoutIfNeeded()。它会改变发际线的框架。在下面编写一个函数并在您的段控件的操作方法中调用此函数:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let segmentControlFrame = self.view.convert(segmentControl.frame, from: segmentControl.superview)
let widthForHairLine = segmentControlFrame.width / 4
if segmentControl.selectedSegmentIndex == 0 {
firstFrame = CGRect(x: segmentControlFrame.minX, y: segmentControlFrame.maxY , width: widthForHairLine, height: 5)
} else if segmentControl.selectedSegmentIndex == 1 {
firstFrame = CGRect(x: (segmentControlFrame.minX + widthForLine), y: segmentControlFrame.maxY , width: widthForHairLine, height: 5)
} else if segmentControl.selectedSegmentIndex == 2 {
firstFrame = CGRect(x: (segmentControlFrame.minX + widthForLine + widthForLine), y: segmentControlFrame.maxY , width: widthForHairLine, height: 5)
} else if segmentControl.selectedSegmentIndex == 3 {
firstFrame = CGRect(x: (segmentControlFrame.minX + widthForLine + widthForLine + widthForLine), y: segmentControlFrame.maxY , width: widthForHairLine, height: 5)
self.hairline.backgroundColor = UIColor.red
self.hairline.frame = firstFrame!
self.hairline.layoutIfNeeded()
}
关于ios - 在 Swift 的分段控件中选择任何分段时如何创建和突出显示红色细线(向下),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39146828/