【问题标题】:Swift -How to get the center frame of a button's titleLabel and not the button itselfSwift - 如何获取按钮标题标签的中心框架而不是按钮本身
【发布时间】:2021-01-15 15:10:25
【问题描述】:

我有一个自定义分段控件,其中包含 4 个分段,每个分段中有一个按钮。我不得不对按钮的 contentEdgeInsets 进行更改:

// eg of the second button
customSegmentedControl.secondButton?.contentEdgeInsets = UIEdgeInsets(top: 0, left: -35, bottom: 0, right: 0)

滑块最初使用button.frame.midX 滑动到每个段。更改contentEdgeInsets 后,当滑块滑动到某个段时,它看起来好像在错误的位置,因为标题不再位于按钮的中心。我尝试将滑块更改为滑动到按钮 button.titleLabel:button.titleLabel!.frame.midX 的中心,但是在滑块滑动不正确的地方出现了一个奇怪的错误。

for button in buttons {
            
    UIView.animate(withDuration: 0.2, animations: {

        self.slider.frame.origin.x = button.titleLabel!.frame.midX // button.frame.midX was what was originally used
         // if it's the selected button break ...
    })
}

如何让滑块滑动到按钮titleLabel 的中心?例如,我希望它滑动到 Pencil 这个单词的中间,这是按钮的标题,其 contentEdgeInsets 已更改,而不是按钮本身的中间。

【问题讨论】:

    标签: ios swift uibutton


    【解决方案1】:

    这只是坐标系的问题。你不知道button.titleLabel!.frame 在哪个坐标系中,所以你有这个CGRect 但它对你没有用。

    但您确实知道 滑块 frame 需要在哪个坐标系中;就其superview而言。

    所以转换button.titleLabel!.frame到滑块的superview的坐标系,现在你可以有意义地移动滑块了。

    let convertedRect = slider.superview!.convert(button.titleLabel!.frame, from: button.titleLabel!)
    

    【讨论】:

    • 感谢您的回答,我刚刚接到一个重要电话,等我完成后我会尝试一下并回复您。
    • 是的,我以前听说过这个:)
    • 无法使用类型为“(来自:UILabel)”的参数列表调用“convert”
    • 已修复,我在头顶打字
    • 您不希望滑块的origin.x 位于按钮的中间吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-23
    • 2018-05-29
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多