【问题标题】:How to set a buttons constraints equal to the safe area in Swift?如何设置按钮约束等于 Swift 中的安全区域?
【发布时间】:2020-11-04 03:21:01
【问题描述】:

我有一个 UIButton 的简单代码:

let myButton = UIButton()
        myButton.setImage(#imageLiteral(resourceName: "cross"), for: .normal)
        myButton.tintColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)

        view.addSubview(myButton)

我想将按钮设置为位于屏幕左上方。我尝试使用 CGRect 框架,但这并没有达到我想要的效果。我试图弄清楚如何将按钮的左侧放在安全区域,将按钮的顶部放在安全区域,尽管我不知道该怎么做。 (我对编码有点陌生,并且一直在使用故事板......)

【问题讨论】:

    标签: swift uibutton constraints nslayoutconstraint


    【解决方案1】:

    搜索一下自动布局教程。

    但是,让你开始......

        let myButton = UIButton()
        myButton.setImage(#imageLiteral(resourceName: "cross"), for: .normal)
        myButton.tintColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        myButton.translatesAutoresizingMaskIntoConstraints = false
        
        view.addSubview(myButton)
        
        let g = view.safeAreaLayoutGuide
    
        NSLayoutConstraint.activate([
            // constrain button 20-pts from top and leading
            myButton.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
            myButton.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
        ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-17
      • 1970-01-01
      • 2015-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-21
      相关资源
      最近更新 更多