我是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
我不确定这是错的。另外,这些方法在上面用来实现我的目标吗?
谢谢。答案 0 :(得分:0)
此约束使屏幕显示为当前right_of_button = right_of_screen + 80仅显示20个点,因为它的宽度为100
navigationBtn.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: 80).isActive = true
应该是从屏幕右侧说出20分
navigationBtn.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -20).isActive = true
将其关闭屏幕