UIScrollView
in codeI'm self-taught to make an app, but by the way, I thought I had never used scrollView
, so I studied!
First, I tried using scrollView
without looking at it at all.
Here is the code
class ViewController: UIViewController {
private let label = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
let scrollView = UIScrollView()
scrollView.frame = .init(x: 0, y: 0,
width: view.frame.size.width, height: view.frame.size.height)
view.addSubview(scrollView)
scrollView.addSubview(label)
label.text = "hello world"
label.frame = .init(x: 0, y: 0, width: 100, height: 50)
label.center = scrollView.center
}
}
The result could not be scrolled.
label
is added to make sure that scrollView
is displayed properly.
why! ?? It seems that you have to specify something called contentSize
.
contentSize
seems to determine the scroll area.
Here is the corrected one
class ViewController: UIViewController {
private let label = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
let scrollView = UIScrollView()
//Set the size of scrollView.
scrollView.frame = .init(x: 0, y: 0,
width: view.frame.size.width * 2, height: view.frame.size.height * 2)
//Scroll area settings
scrollView.contentSize = CGSize(width:view.frame.size.width * 2, height:view.frame.size.height * 2)
//Add scrollView as SubView of view
view.addSubview(scrollView)
scrollView.addSubview(label)
label.text = "hello world"
label.frame = .init(x: 0, y: 0, width: 100, height: 50)
label.center = scrollView.center
}
}
How about this! I built it, but I couldn't scroll.
Upon further investigation, it seems that frame
must be smaller than contentSize
.
class ViewController: UIViewController {
private let label = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
let scrollView = UIScrollView()
//Set the size of scrollView.
scrollView.frame = .init(x: 0, y: 0,
width: view.frame.size.width, height: view.frame.size.height)
//Scroll area settings
scrollView.contentSize = CGSize(width:view.frame.size.width * 2, height:view.frame.size.height * 2)
//Add scrollView as SubView of view
view.addSubview(scrollView)
scrollView.addSubview(label)
label.text = "hello world"
label.frame = .init(x: 0, y: 0, width: 100, height: 50)
label.center = scrollView.center
}
}
The result is ... I got it! !! !!
When using UIScrollView
contentSize
must be specifiedcontentSize
must be larger thanframe
Please note that and implement it!
[Swift4] How to use scroll view
Recommended Posts