【问题标题】:UiButton and translatesAutoresizingMaskIntoConstraintsUiButton 和 translatesAutoresizingMaskIntoConstraints
【发布时间】:2015-10-20 20:36:05
【问题描述】:

我的问题很简单。

我目前正在继承 UIButton 以创建一些自定义动画。但是,当我将translatesAutoresizingMaskIntoConstraints 设置为false 时,我的视图会移动到左上角。但是,当我将其设置为 false 或将类更改为 UIViewUIControl 时,此问题不再出现。

这是我的代码:

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    let button = TestA(frame: CGRectMake(100, 100, 100, 100))
    button.backgroundColor = UIColor.blackColor()
    self.view.addSubview(button)

    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}


class TestA : UIControl {


required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

override init(frame: CGRect) {
    super.init(frame: frame)
}


}

有人知道发生了什么吗?

【问题讨论】:

    标签: ios swift uibutton autolayout


    【解决方案1】:

    例如,您有职位A 和职位B。对于位置 A,您添加了约束并将其固定在其位置。如果你只是输入例如button.frame = CGRectMake(0.0.100.100)它不会从当前位置移动,因为它是固定的,在这种情况下如果我们想要实现移动我们需要使用translatesAutoresizingMaskIntoConstraints并且我们应该将它设置为true,之后我们就有可能更改UIButton 的位置。希望对您有所帮助。

    【讨论】:

    • 首先我很抱歉,我应该添加代码以供审查。无论是UIButtonUIView 还是UIControl,帧在所有情况下都被硬编码为button.frame = CGRect(100,100,100,100)。但是,此行为仅在 UIButton 时才会出现。
    • translatesAutoresizingMaskIntoConstraints 这适用于 uibutton、UiView 等,但如果你有硬编码位置并且你试图解锁约束,它将跳转到 x:0, y:0 。
    猜你喜欢
    • 1970-01-01
    • 2014-08-15
    • 1970-01-01
    • 2013-06-11
    • 2018-05-27
    • 2023-03-13
    • 1970-01-01
    • 2012-09-24
    • 2011-03-07
    相关资源
    最近更新 更多