我在启动时修改UIView高度时遇到问题。
我必须使用UIView,我希望一个屏幕大小*70,另一个填补空白。
这是我的
@IBOutlet weak var questionFrame: UIView!
@IBOutlet weak var answerFrame: UIView!
let screenSize:CGRect = UIScreen.mainScreen().bounds
和
questionFrame.frame.size.height = screenSize.height * 0.70
answerFrame.frame.size.height = screenSize.height * 0.30
它在运行时对应用程序没有影响。我使用自动布局,但我只有边距限制。。。
我做错了吗?
这可以在Swift 3.0中通过各种方法实现在2019年5月的最新版本上工作
直接指定Height&视图的宽度值:
userView.frame.size.height = 0
userView.frame.size.width = 10
为帧分配CGRect
userView.frame = CGRect(x:0, y: 0, width:0, height:0)
方法详细信息:
CGRect(x:x点,y:y点,宽度:视图宽度,高度:视野高度)
使用CGRECT的扩展方法
在任何swift文件中添加以下扩展码,
extension CGRect {
init(_ x:CGFloat, _ y:CGFloat, _ w:CGFloat, _ h:CGFloat) {
self.init(x:x, y:y, width:w, height:h)
}
}
在应用程序中的任何位置使用以下代码来设置视图的尺寸参数
userView.frame = CGRect(1, 1, 20, 45)
开始吧。这应该行得通。
questionFrame.frame = CGRectMake(0 , 0, self.view.frame.width, self.view.frame.height * 0.7)
answerFrame.frame = CGRectMake(0 , self.view.frame.height * 0.7, self.view.frame.width, self.view.frame.height * 0.3)
Swift 3和Swift 4:
myView.frame = CGRect(x: 0, y: 0, width: 0, height: 0)
Hi-create this extends if you want更新2021 Swift 5
创建文件扩展。Swift和添加此代码(在需要更改高度的地方添加导入基础)
extension UIView {
var x: CGFloat {
get {
self.frame.origin.x
}
set {
self.frame.origin.x = newValue
}
}
var y: CGFloat {
get {
self.frame.origin.y
}
set {
self.frame.origin.y = newValue
}
}
var height: CGFloat {
get {
self.frame.size.height
}
set {
self.frame.size.height = newValue
}
}
var width: CGFloat {
get {
self.frame.size.width
}
set {
self.frame.size.width = newValue
}
}
}
使用(继承UIView)
inheritsOfUIView.height = 100
button.height = 100
print(view.height)
对于进度条之类的东西,在Swift 4 中
我遵循以下步骤:
- 我创建了一个UIView出口:
@IBOutlet var progressBar: UIView!
- 然后是在用户操作
var progressBarWidth: Int = your value
之后增加其宽度值的属性 - 则对于进度的增加/减少
progressBar.frame.size.width = CGFloat(progressBarWidth)
- 最后,在IBACtion方法中,我添加了
progressBarWidth += your value
,用于每次用户触摸按钮时自动增加宽度
分配questionFrame.frame.size.height= screenSize.height * 0.30
不会在视图中反映任何内容。因为这是一处仅限获取的房产。如果你想更改questionFrame的框架,你可以使用下面的代码。
questionFrame.frame = CGRect(x: 0, y: 0, width: 0, height: screenSize.height * 0.70)
您可以在界面生成器中执行此操作:
-
控制从框架视图(例如questionFrame)到主视图的拖动,在弹出窗口中选择等高。
-
然后转到框架的尺寸检查器,单击编辑等于Superview约束的高度,将乘数设置为0.7,然后点击回车键。
您将看到约束已从等高到…到成比例高度到….
我知道这个问题已经有了解决方案,但我找到了这个问题的替代方案,也许它可以帮助别人。
我在设置子视图的框架时遇到了问题,因为某些值指的是它在主视图中的位置。因此,如果你不想通过CGRect更改整个帧来更新你的帧,你可以简单地更改帧的一个值,然后更新它。
// keep reference to you frames
var questionView = questionFrame.frame
var answerView = answerFrame.frame
// update the values of the copy
questionView.size.height = CGFloat(screenSize.height * 0.70)
answerView.size.height = CGFloat(screenSize.height * 0.30)
// set the frames to the new frames
questionFrame.frame = questionView
answerFrame.frame = answerView