Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/102.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 以编程方式添加内容后调整uiscrollview的大小_Ios_Uiscrollview - Fatal编程技术网

Ios 以编程方式添加内容后调整uiscrollview的大小

Ios 以编程方式添加内容后调整uiscrollview的大小,ios,uiscrollview,Ios,Uiscrollview,我有一个在Uiscrollview中包含uielements的Contentview。下面是我的故事板截图: 我想为应用程序添加一个选项,如果用户单击该按钮,它将在contentview的底部添加标签(在红色下划线标签-dzialTerminOutlet下面)。 我使用以下代码以编程方式添加新标签: let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.backgroundCo

我有一个在Uiscrollview中包含uielements的Contentview。下面是我的故事板截图:

我想为应用程序添加一个选项,如果用户单击该按钮,它将在contentview的底部添加标签(在红色下划线标签-dzialTerminOutlet下面)。

我使用以下代码以编程方式添加新标签:

let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false

label.backgroundColor = UIColor.orange
label.textColor = UIColor.black
label.textAlignment = NSTextAlignment.center
label.text = "test label"
contentView.addSubview(label)


label.topAnchor.constraint(equalTo: dzialTerminOutlet.bottomAnchor, constant: 10).isActive = true
label.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 85.0)
label.widthAnchor.constraint(equalToConstant: 200.0)
label.heightAnchor.constraint(equalToConstant: 10.0)

但scrollview不会调整大小。这里有什么问题?

您是否将scrollView内容大小设置为新大小?
scrollView.contentSize=CGSize(宽度:self.contentView.frame.size.width,高度:self.contentView.frame.size.height)

1-您需要激活

NSLayoutConstraint.activate([
  label.topAnchor.constraint(equalTo: dzialTerminOutlet.bottomAnchor, constant: 10),
  label.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 85.0),
  label.widthAnchor.constraint(equalToConstant: 200.0),
  label.heightAnchor.constraint(equalToConstant: 10.0)
])
2-您需要删除IB中在
dzialTerminOutlet
contentView
之间建立的底部约束,以便能够插入新的约束并相应调整滚动视图的大小,以避免其与

label.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 85.0)

因此,将其挂接为一个outlet并将其停用,或者搜索contentView以查找底部约束并将其删除。

我经常使用的一种非常简单的方法是将contentView高度约束与IBOutlet对象连接起来,并更新其值

@IBOutlet weak var contentViewHeight : NSLayoutConstraint!
添加标签后:

contentViewHeight.constant += labelHeight

别忘了使用滚动视图设置contentView约束(顶部、底部、前导、尾随)=0

我觉得你的答案非常符合逻辑。但是,在我禁用底部约束(dzialTerminBottomConstraint.isActive=false)后,scrollview会缩短85 px