【问题标题】:add constrains for button programmatically in my view. swift 4在我看来,以编程方式为按钮添加约束。迅速 4
【发布时间】:2018-04-14 22:43:40
【问题描述】:

我是 swift 新手,我想为按钮添加约束以适应所有屏幕。按钮的位置在视图的右上角。具体来说,该按钮出现在谷歌地图上。

首先,当我添加一个没有约束的按钮时,它会正常显示:

有效代码:

let navigationBtn = UIButton(frame: CGRect(x: 350, y: 50, width: 100, height: 100)) navigationBtn.setTitle("", for: .normal) navigationBtn.setTitleColor(.red, for: .normal) navigationBtn.addTarget(self, action:#selector(self.buttonClicked(sender:)), for: .touchUpInside) navigationBtn.setImage(UIImage(named: "map.png"), for: .normal) self.view.addSubview(navigationBtn)

然后我尝试这段代码以确保我的按钮适合,但是当我运行模拟器时,按钮消失了。我使用了以下代码:

  let navigationBtn = UIButton()
        navigationBtn.addTarget(self, action:#selector(self.buttonClicked(sender:)), for: .touchUpInside)
        navigationBtn.setImage(UIImage(named: "map.png"), for: .normal)
        self.view.addSubview(navigationBtn)

        navigationBtn.translatesAutoresizingMaskIntoConstraints = false
        navigationBtn.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: 80).isActive = true
        navigationBtn.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 80).isActive = true
        navigationBtn.widthAnchor.constraint(equalToConstant: 100).isActive = true
        navigationBtn.heightAnchor.constraint(equalToConstant: 100).isActive = true

我不确定出了什么问题。另外,上面的这些方法是用来实现我的目标的吗?

谢谢。

【问题讨论】:

    标签: ios uiview uibutton constraints swift4


    【解决方案1】:

    这个约束使它在屏幕上显示为当前 right_of_button = right_of_screen + 80 只有 20 pts 将显示为它的宽度为 100

      navigationBtn.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: 80).isActive = true
    

    如果说它距离屏幕右侧 20 点应该是

      navigationBtn.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -20).isActive = true
    

    让它离开屏幕

    【讨论】:

    • 谢谢它对我有用。还有一个问题意味着现在我的按钮位置适合所有屏幕?
    • 它适用于所有屏幕,但问题是常量不会改变它会从顶部开始 80 和从右边开始 20 用于与 iphone 4 相比外观不同的所有设备和 8 加
    • 您可以检测当前设备并相应设置常数
    猜你喜欢
    • 2021-05-02
    • 2015-09-24
    • 2021-08-09
    • 2015-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多