微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

子类化 UIControl

如何解决子类化 UIControl

我正在尝试创建一个自定义的 Segment 控件,它需要看起来像这样:

enter image description here

为了完成这件事,我已经关注了 this youtube tutorial,并且在大多数情况下,我最终得到了这样的结果:

enter image description here

按照教程,一切正常,但是如果你注意到我上面的设计,黄色的选定视图需要一点填充,教程没有这个,因为选择视图像这样接触容器的边界:

enter image description here

我从教程中更改的唯一部分是在 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 举报,一经查实,本站将立刻删除。