问题描述
我正在尝试创建一个自定义的 Segment 控件,它需要看起来像这样:
为了完成这件事,我已经关注了 this youtube tutorial,并且在大多数情况下,我最终得到了这样的结果:
按照教程,一切正常,但是如果你注意到我上面的设计,黄色的选定视图需要一点填充,教程没有这个,因为选择视图像这样接触容器的边界:
我从教程中更改的唯一部分是在 layoutSubviews
中添加我自己的计算,如下所示:
override func layoutSubviews() {
superview?.layoutSubviews()
layer.cornerRadius = frame.height / 2
// This line has the issue
var selectFrame = self.bounds
let newWidth = (selectFrame.width / CGFloat(segmentTitles.count))
selectFrame.size.width = newWidth
thumbView.frame = selectFrame
thumbView.backgroundColor = .panoStoryYellow
thumbView.layer.cornerRadius = thumbView.frame.height / 2
let labelHeight = self.bounds.height
let labelWidth = (self.bounds.width / CGFloat(segmentTitles.count))
for index in 0..<segmentLabels.count {
let label = segmentLabels[index]
let xPos = (CGFloat(index) * labelWidth)
label.frame = CGRect(x: xPos,y: 0,width: labelWidth,height: labelHeight)
}
}
使用此代码,一切正常。
但是当我将上面的代码更改为此行 var selectFrame = self.bounds
到
CGRect(x: self.bounds.origin.x + 4,y: self.bounds.origin.y + 4,width: self.bounds.width - 8,height: self.bounds.height - 8)
为了添加一些填充,黄色的选定视图不会移动,而是卡在第一段而不是移动到下一段。
我的控件完整源代码可以是found here
我不确定我做错了什么。
是否有一些限制/限制,在 UIControl 中包含视图需要占据完整的边界?
如果有人能指出我正确的方向,我们将不胜感激。
提前致谢。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)