将按钮绑定到视图的右上角 iOS swift
Posted
技术标签:
【中文标题】将按钮绑定到视图的右上角 iOS swift【英文标题】:Bound the button to top right corner of the view iOS swift 【发布时间】:2016-05-20 09:29:05 【问题描述】:我有一个视图,其中我有多个标签and 一个按钮,我希望按钮绑定到右上角
当我应用添加缺少约束布局时,按钮会为不同的设备获得单独的位置请帮我解决这个问题
【问题讨论】:
添加缺少约束是一个不好的选择......只需根据需要逐个设置约束 永远不要使用“添加缺少的约束” - 始终自己添加约束。 对于右上角,您需要设置约束,例如:尾随:0,顶部:0 固定高度和固定宽度 我对标签有同样的问题,如何将它放在底部和中心 【参考方案1】:永远不要使用add missing constraints
。这是构建布局的不好方法。
获得所需外观的最简单方法是确定按钮的大小(例如 30x30)
然后您将以下约束添加到您的按钮:
这会设置按钮的宽度和高度:
然后将其固定在右上角:
【讨论】:
我有一个标签,里面有字符串名称和整数值我想加粗整数值而不影响字符串你可以解决这个问题【参考方案2】://以防万一有人需要代码:
//I have added 4 buttons to a custom view's each corner:
var customView = UIView()
override func viewDidLoad()
super.viewDidLoad()
customView.frame = CGRect.init(x: 0, y: 0, width: 200, height: 200)
customView.backgroundColor = UIColor.red //give color to the view
customView.center = self.view.center
let crossButton = UIButton(frame: CGRect(x: -10, y: -10, width: 30, height: 30))
crossButton.layer.cornerRadius = 15
crossButton.backgroundColor = UIColor.black
crossButton.setImage(UIImage(named: "cross.png"), for: .normal)
crossButton.addTarget(self, action: #selector(crossButtonTapped), for: .touchUpInside)
crossButton.autoresizingMask = [.flexibleLeftMargin, .flexibleBottomMargin]
let flipButton = UIButton(frame: CGRect(x: customView.frame.width-15, y: -10, width: 30, height: 30))
flipButton.layer.cornerRadius = 15
flipButton.backgroundColor = UIColor.black
flipButton.setImage(UIImage(named: "done.png"), for: .normal)
flipButton.addTarget(self, action: #selector(crossButtonTapped), for: .touchUpInside)
flipButton.autoresizingMask = [.flexibleLeftMargin, .flexibleBottomMargin]
let scaleButton = UIButton(frame: CGRect(x: -10, y: customView.frame.height-20, width: 30, height: 30))
scaleButton.layer.cornerRadius = 15
scaleButton.backgroundColor = UIColor.black
scaleButton.setImage(UIImage(named: "done.png"), for: .normal)
scaleButton.addTarget(self, action: #selector(crossButtonTapped), for: .touchUpInside)
scaleButton.autoresizingMask = [.flexibleLeftMargin, .flexibleBottomMargin]
let editButton = UIButton(frame: CGRect(x: customView.frame.width-20, y: customView.frame.height-20, width: 30, height: 30))
editButton.layer.cornerRadius = 15
editButton.backgroundColor = UIColor.black
editButton.setImage(UIImage(named: "done.png"), for: .normal)
editButton.addTarget(self, action: #selector(crossButtonTapped), for: .touchUpInside)
editButton.autoresizingMask = [.flexibleLeftMargin, .flexibleBottomMargin]
customView.addSubview(crossButton)
customView.addSubview(flipButton)
customView.addSubview(scaleButton)
customView.addSubview(editButton)
self.view.addSubview(customView)
func crossButtonTapped(_ sender:UIButton)
print("Cross Button was tapped")
【讨论】:
以上是关于将按钮绑定到视图的右上角 iOS swift的主要内容,如果未能解决你的问题,请参考以下文章
创建视图控制器并将现有 VC 的标签和按钮添加到新的 VC Swift iOS