ImageView和Label未填充父级(UIScrollView)

时间:2015-10-29 17:51:12

标签: ios swift

我有一个UIScrollView,我试图在scrollview中添加一个UIImageView。但在那之后,我想在imageview中找到一个UILabel。基本上,图像应填充滚动视图,标签应出现在图像的中心。这就是我所拥有的:

@IBOutlet weak var image_scroll_view: UIScrollView!
var imageView = UIImageView()
override func viewDidLoad() {
    super.viewDidLoad()
    image_scroll_view.backgroundColor = UIColor.yellowColor()

    imageView.frame = CGRectMake(0, 0, image_scroll_view.frame.size.width, image_scroll_view.frame.height)
    imageView.userInteractionEnabled = true
    imageView.contentMode = UIViewContentMode.ScaleAspectFit
    imageView.backgroundColor = UIColor.greenColor()

    image_scroll_view.scrollRectToVisible(imageView.frame, animated: true)

    self.imageView.image = // ...

    let curr_user_name = UILabel(frame: CGRectMake(0, 0, imageView.frame.width, imageView.frame.height))
    curr_user_name.text = "John Smith"
    curr_user_name.textColor = UIColor.whiteColor()
    curr_user_name.font = UIFont.boldSystemFontOfSize(16.0)
    curr_user_name.backgroundColor = UIColor.redColor()
    curr_user_name.center = CGPointMake(imageView.center.x, imageView.center.y)
    curr_user_name.textAlignment = NSTextAlignment.Center
    imageView.addSubview(curr_user_name)
    image_scroll_view.addSubview(imageView)
    self.navigationController?.navigationBarHidden = true
}

这是它的样子:

enter image description here

滚动视图为黄色。理想情况下,图像视图应该填充所有这些(此时甚至不显示),标签应该填充所有图像视图,这将自动居中文本。

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

使cur_user_name成为一个属性 写下这段代码:

imageView.frame = CGRectMake(0, 0, image_scroll_view.frame.size.width, image_scroll_view.frame.height)

curr_user_name.center = CGPointMake(imageView.center.x, imageView.center.y)

在viewDidLayoutSubviews