我有一个视图,我通过xib添加按钮以编程方式创建另一个视图。我可以创建多个视图点击添加更多按钮和删除也工作,如果我删除最后一个视图但问题发生中间视图由于缺少约束视图没有正确更新下面是图像如何看
在开始视图中看起来像这样
添加更多视图后
删除中间视图后
删除按钮代码
@IBAction func deletebnt(_ sender: UIButton) {
let view = self.superview
let index = view?.subviews.index(of:self)!
delegate.txtcheck(text: countstr)
self.view.removeFromSuperview()
}
添加按钮代码
@IBAction func addMoreBnt(_ sender: UIButton) {
for constraint in addSuperview.constraints {
if constraint.firstAttribute == NSLayoutAttribute.height
{
constraint.constant += 45
space = constraint.constant
}
}
let newView : AvalabileTimeView = AvalabileTimeView()
newView.frame = CGRect(x: self.addsubView.frame.origin.x, y: 70, width: addsubView.frame.size.width, height:addsubView.frame.size.height)
newView.delegate = self as AvalabileTimeDelegate
addSuperview.addSubview(newView)
let index = addSuperview.subviews.index(of: newView)!
newView.translatesAutoresizingMaskIntoConstraints = false
let heightConstraint = newView.widthAnchor.constraint(equalToConstant:addsubView.frame.size.width )
let widthConstaint = newView.heightAnchor.constraint(equalToConstant:31 )
let topConstraint = newView.topAnchor.constraint(equalTo: addSuperview.topAnchor, constant: space - 31) NSLayoutConstraint.activate([heightConstraint,topConstraint,widthConstaint])
}
委托更改超级视图的高度
func txtcheck(text: String!) {
print(text)
for constraint in addSuperview.constraints {
if constraint.firstAttribute == NSLayoutAttribute.height
{
constraint.constant -= 45
// Here I have to set constraint for bottom view and topview of deleted view but I don't know how to do
}
}
}
答案 0 :(得分:3)
不是使用自己的约束添加每个新AvalabileTimeView
,而是使用UIStackView
- 您可以删除几乎所有现有代码,以添加/删除新视图。
查看.addArrangedSubview()
和.removeArrangedSubview()
以下是一些示例代码...您需要在Interface Builder中添加UIStackView,将其连接到Outlet,并调整约束,但这些都是关于所有的:
// in ViewController.swift
@IBOutlet weak var availableTimeStackView: UIStackView!
@IBAction func addMoreBnt(_ sender: UIButton) {
// instantiate a new AvalabileTimeView
let newView : AvalabileTimeView = AvalabileTimeView()
// set its delegate to self
newView.delegate = self as AvalabileTimeDelegate
// add it to the Stack View
availableTimeStackView.addArrangedSubview(newView)
// standard for auto-layout
newView.translatesAutoresizingMaskIntoConstraints = false
// only constraint needed is Height (width and vertical spacing handled by the Stack View)
newView.heightAnchor.constraint(equalToConstant: 31).isActive = true
}
// new delegate func
func removeMe(_ view: AvalabileTimeView) {
// remove the AvalabileTimeView from the Stack View
availableTimeStackView.removeArrangedSubview(view)
}
// in AvalabileTimeView.swift
protocol AvalabileTimeDelegate{
// don't need this anymore
func txtcheck(text: String!)
// new delegate func
func removeMe(_ view: AvalabileTimeView)
}
@IBAction func deletebnt(_ sender: UIButton) {
delegate.removeMe(self)
}