如何在 swift 中动态设置帧?
how to set frame dynamically in swift?
我正在尝试将 imageview 设置为 scrollview.for 的子视图,我设置不同的框架取决于屏幕尺寸。
这是我的代码
let screensize:CGRect=UIScreen.mainScreen().bounds
let screenwidth=screensize.width
var frames:CGRect
for var index=0 ;index < arrBirds.count ;index++
{
if(screenwidth==320)
{
frames.origin.x = CGFloat(index) * (self.view.frame.size.width);
frames.origin.y = 0;
frames.size=scrollview.frame.size;
}
else if(screenwidth==375)
{
frames.origin.x = CGFloat(index) * (self.view.frame.size.width);
frames.origin.y=0;
frames.size=scrollview.frame.size;
}
else
{
frames.origin.x = CGFloat(index) * (self.view.frame.size.width);
frames.origin.y=0;
frames.size=scrollview.frame.size;
}
imageView=UIImageView(frame:frames)
imageView.image=UIImage(named: arrBirds[index] as! String)
scrollview .addSubview(imageView)
但是我在这行遇到错误
frames.origin.x = CGFloat(index) * (self.view.frame.size.width);//struct frame must be completely initialised before a member is stored to.
您还没有创建结构 CGRect
的实例。在访问/设置任何成员之前,您需要先创建一个实例,然后仅在那之后设置它的不同成员:
将行 var frames:CGRect
更改为:
var frames = CGRectZero
根据Apple Docs:
Classes and structures must set all of their stored properties to an
appropriate initial value by the time an instance of that class or
structure is created.
您的 frames
对象未初始化,您应该这样写:
var frames = CGRectZero
我正在尝试将 imageview 设置为 scrollview.for 的子视图,我设置不同的框架取决于屏幕尺寸。
这是我的代码
let screensize:CGRect=UIScreen.mainScreen().bounds
let screenwidth=screensize.width
var frames:CGRect
for var index=0 ;index < arrBirds.count ;index++
{
if(screenwidth==320)
{
frames.origin.x = CGFloat(index) * (self.view.frame.size.width);
frames.origin.y = 0;
frames.size=scrollview.frame.size;
}
else if(screenwidth==375)
{
frames.origin.x = CGFloat(index) * (self.view.frame.size.width);
frames.origin.y=0;
frames.size=scrollview.frame.size;
}
else
{
frames.origin.x = CGFloat(index) * (self.view.frame.size.width);
frames.origin.y=0;
frames.size=scrollview.frame.size;
}
imageView=UIImageView(frame:frames)
imageView.image=UIImage(named: arrBirds[index] as! String)
scrollview .addSubview(imageView)
但是我在这行遇到错误
frames.origin.x = CGFloat(index) * (self.view.frame.size.width);//struct frame must be completely initialised before a member is stored to.
您还没有创建结构 CGRect
的实例。在访问/设置任何成员之前,您需要先创建一个实例,然后仅在那之后设置它的不同成员:
将行 var frames:CGRect
更改为:
var frames = CGRectZero
根据Apple Docs:
Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created.
您的 frames
对象未初始化,您应该这样写:
var frames = CGRectZero