Swift 如何在景观中重绘子视图
大家下午好 我正试图通过扩展向viewcontroller添加两个子视图,但在旋转设备时,它不考虑布局,有没有关于如何使其看起来正确的选项 我在下面附上我的代码和几张示例照片,第一张照片是我希望它看起来如何,而ui的其余部分丢失了 这是我的代码:Swift 如何在景观中重绘子视图,swift,swift5.4,Swift,Swift5.4,大家下午好 我正试图通过扩展向viewcontroller添加两个子视图,但在旋转设备时,它不考虑布局,有没有关于如何使其看起来正确的选项 我在下面附上我的代码和几张示例照片,第一张照片是我希望它看起来如何,而ui的其余部分丢失了 这是我的代码: func presentCustomAlertController(on ViewController:UIViewController,toPresentCustomView customView:UIView,withBackgroundV
func presentCustomAlertController(on ViewController:UIViewController,toPresentCustomView customView:UIView,withBackgroundView backGroundView:UIView){
customView.translatesAutoresizingMaskIntoConstraints = false
guard let targetView = ViewController.view else {return}
backGroundView.alpha = 0
backGroundView.backgroundColor = .black
backGroundView.frame = targetView.bounds
targetView.addSubview(backGroundView)
targetView.addSubview(customView)
customView.setNeedsLayout()
customView.setNeedsDisplay()
customView.layoutIfNeeded()
customView.layoutSubviews()
targetView.setNeedsLayout()
targetView.setNeedsDisplay()
targetView.layoutIfNeeded()
targetView.layoutSubviews()
backGroundView.setNeedsDisplay()
backGroundView.setNeedsLayout()
backGroundView.layoutIfNeeded()
customView.frame = CGRect(x: targetView.center.x, y: targetView.center.y, width: targetView.frame.size.width-80, height: 300)
UIView.animate(withDuration: 0.25, animations: {
backGroundView.alpha = 0.6
},completion: { done in
UIView.animate(withDuration: 0.25, animations: {
customView.center = targetView.center
})
})
}
}仅供参考:该行
customView.center=targetView.center
的功能与您可能认为的不同。特别是,它不在targetView
@matt内居中customView
,您建议我在不使用属性中心的情况下居中查看该视图吗?不知道,因为您没有显示足够的信息。您说的是customView.translatesAutoresizingMaskIntoConstraints=false
,这表明您有自动布局约束。但是您没有显示它们是什么,在任何情况下,这将导致设置中心
中断,因为中心
/帧
和自动布局是相反的。你不能两者都用;它们会互相争斗。通常情况下,这并不是将自定义视图控制器显示为中心警报的方式。