Swift2 使用堆栈视图时帧值不正确
我将两个图像放在一个堆栈视图中。我想通过编程将这两个正方形图像转换为圆形,因此我使用以下代码Swift2 使用堆栈视图时帧值不正确,swift2,xcode7,ios9,uistackview,Swift2,Xcode7,Ios9,Uistackview,我将两个图像放在一个堆栈视图中。我想通过编程将这两个正方形图像转换为圆形,因此我使用以下代码 class ProfileViewController: UIViewController { @IBOutlet weak var image1: UIImageView! @IBOutlet weak var image2: UIImageView! override viewDidLoad(){ // Convert image one into circ
class ProfileViewController: UIViewController {
@IBOutlet weak var image1: UIImageView!
@IBOutlet weak var image2: UIImageView!
override viewDidLoad(){
// Convert image one into circle
self.image1.layer.cornerRadius = self.image1.frame.height/2
self.image1.clipsToBounds = true
// Convert image two into circle
self.image2.layer.cornerRadius = self.image2.frame.height/2
self.image2.clipsToBounds = true
// Print the frames of these two images
print(self.image1.frame)
print(self.image2.frame)
}
}
在示例中,帧的x和y值无关紧要,但奇怪的是,宽度和高度值最终都为零,尽管“检查器”选项卡上的值为零
如果我在屏幕上添加一个按钮,然后打印出两幅图像的帧,我会得到预期的宽度和高度值。因此,我假设堆栈视图在激发
viewDidLoad()
方法之后确定对象的尺寸。在这种情况下,获得实际帧尺寸的最佳方法是什么,以便将两幅图像四舍五入?或者使用帧以外的值是更好的解决方案吗?在您的情况下,由于您尝试访问图像视图的帧并使用UIStackView,因此帧实际上将首先在viewDidLayoutSubviews()中布局。因此,要获得所需的圆形图像,首先需要为堆栈视图创建一个插座,如下所示:
class ProfileViewController: UIViewController {
@IBOutlet weak var verticalStackView: UIStackView!
...
然后在viewDidLayoutSubviews()
方法中,访问堆栈视图的arrangedSubviews
索引,以获取图像所在的视图(索引可以从堆栈视图层次结构中确定,从上到下),然后按照所做的操作获取圆角:
class ProfileViewController: UIViewController {
@IBOutlet weak var verticalStackView: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidLayoutSubviews() {
let myImage = verticalStackView.arrangedSubviews[1] //in my test my image was the second view in the stack view hierarchy
myImage.layer.cornerRadius = myImage.frame.height/2
myImage.clipsToBounds = true
}
希望这有帮助 在您的情况下,由于您试图访问图像视图的框架并使用UIStackView,因此框架实际上将首先在viewDidLayoutSubviews()
中进行布局。因此,要获得所需的圆形图像,首先需要为堆栈视图创建一个插座,如下所示:
class ProfileViewController: UIViewController {
@IBOutlet weak var verticalStackView: UIStackView!
...
然后在viewDidLayoutSubviews()
方法中,访问堆栈视图的arrangedSubviews
索引,以获取图像所在的视图(索引可以从堆栈视图层次结构中确定,从上到下),然后按照所做的操作获取圆角:
class ProfileViewController: UIViewController {
@IBOutlet weak var verticalStackView: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidLayoutSubviews() {
let myImage = verticalStackView.arrangedSubviews[1] //in my test my image was the second view in the stack view hierarchy
myImage.layer.cornerRadius = myImage.frame.height/2
myImage.clipsToBounds = true
}
希望这有帮助 成功了!我没有发现的是viewdilayoutsubviews()
。非常感谢!成功了!我没有发现的是viewdilayoutsubviews()
。非常感谢!