【问题标题】:Xcode 10 - Scroll View is not allowing scrolling when adding button programmaticallyXcode 10 - 以编程方式添加按钮时,滚动视图不允许滚动
【发布时间】:2019-05-22 04:49:35
【问题描述】:

我正在从数据库中获取数据并尝试将数据显示为按钮,我已经完成了这项工作,但是当我在 Xcode 模拟器上运行应用程序时,按钮正在显示,我可以看到它们不在屏幕上,但我无法滚动。

我尝试在“滚动视图”中添加一个具有固定高度的“视图”,然后将按钮添加到该视图中,但仍然没有。

// Adding the scroll view and the view
@IBOutlet weak var scroll: UIScrollView!
@IBOutlet weak var content: UIView!


// Button Settings
var buttonX = 100
var buttonY = 0
let buttonWidth = 200
let buttonHeight = 50
let image = UIImage(named: "button") as UIImage?

override func viewDidLoad() {
    super.viewDidLoad()

    for element in contentsArray {
         // Adding a button for each client name
         let button = UIButton(type: .system)
         button.setTitle(element, for: .normal)
         button.tintColor = .white
         button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 22)
         button.setBackgroundImage(image, for: .normal)
         button.centerXAnchor.constraint(equalTo: button.centerXAnchor).isActive = true
         button.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)      
         button.frame = CGRect(x: buttonX, y: buttonY, width: buttonWidth, height: buttonHeight)

         content.addSubview(button)

         buttonY = buttonY + 70
    }
}

运行应用程序时,我在控制台中没有收到任何错误。

【问题讨论】:

  • 你必须设置滚动内容大小scrollView.contentSize = CGSize(width: self.view.frame.size.width, height: 700)

标签: ios swift uiscrollview


【解决方案1】:

完成添加按钮后,将 scrollView.contentSize.height 设置为您计算的 buttonY

scrollView.contentSize.width = self.view.frame.size.width // non scrollable content width
for element in contentsArray {
     ...
     buttonY = buttonY + 70
}
scrollView.contentSize.height = buttonY // scrollable content height

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    相关资源
    最近更新 更多