UIScrollView无法滚动?

时间:2017-10-18 17:02:06

标签: ios iphone swift uiscrollview

我已使用UIScrollViewUIImageView设置此UILabel。 但是,它不像我想要的那样滚动。它就像它不在那里......我该如何解决这个问题?我只是希望它可以滚动(即使底部没有任何内容可以滚动到)

提前谢谢!

这是我的代码:

    // scrollView
    scrollView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(scrollView)

    // scrollView constraints
    scrollView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
    scrollView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
    scrollView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
    scrollView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true

    // Initialize profileImageView
    profileImageView.image = #imageLiteral(resourceName: "neil")
    profileImageView.translatesAutoresizingMaskIntoConstraints = false
    profileImageView.layer.cornerRadius = 125 / 2
    profileImageView.clipsToBounds = true
    scrollView.addSubview(profileImageView)

    // Add profileImageView constraints
    profileImageView.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 45).isActive = true
    profileImageView.heightAnchor.constraint(equalToConstant: 125).isActive = true
    profileImageView.widthAnchor.constraint(equalToConstant: 125).isActive = true
    profileImageView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true

    // Add separator view
    seperator.translatesAutoresizingMaskIntoConstraints = false
    seperator.backgroundColor = UIColor.darkGray
    scrollView.addSubview(seperator)

    // seperator constraints
    seperator.heightAnchor.constraint(equalToConstant: 2).isActive = true
    seperator.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 0.8).isActive = true
    seperator.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
    seperator.topAnchor.constraint(equalTo: profileImageView.bottomAnchor, constant: 20).isActive = true

    //nameLabel
    let nameLabelFont = UIFont.monospacedDigitSystemFont(ofSize: 36, weight: UIFont.Weight.heavy)
    nameLabel.font = nameLabelFont
    nameLabel.text = currentUser.name
    nameLabel.translatesAutoresizingMaskIntoConstraints = false
    scrollView.addSubview(nameLabel)

    // nameLabel constraints
    nameLabel.topAnchor.constraint(equalTo: seperator.bottomAnchor, constant: 10).isActive = true
    nameLabel.leadingAnchor.constraint(equalTo: seperator.leadingAnchor).isActive = true

1 个答案:

答案 0 :(得分:1)

您无法滚动,因为scrollView.contentSize不比您的视图大。

如果您想让屏幕可滚动,则应设置scrollView.contentSize

scrollView.contentSize = CGSize(width: 1000, height: 1000)放在view.addSubview(scrollView)之前,将可滚动区域设置为1000x1000。

通常scrollView.contentSize应基于UIScrollView内的UI元素进行计算,例如大小为10张图像,它们之间有空格。