Swift在这里很新,感谢您的耐心等待!
说我想写一个名为ProfileView
的可重用滚动视图,如下所示(问题在下面突出显示):
import UIKit
class ProfileView: UIView, UIScrollViewDelegate {
var profileView: UIScrollView!
var profile: Profile! // Profile is a custom class
// It contains user's profile, name, etc
init (frame: CGRect, profile: Profile) {
super.init(frame: frame)
profileScrollView = UIScrollView(frame: frame)
self.profile = profile
loadView()
}
func loadView() {
profileScrollView.delegate = self
// Then go ahead and display user's profile info such as
// their names and profile pictures etc
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
print("\(scrollView.contentOffset.y)")
}
}
你可能已经注意到,ProfileView
也继承自UIScrollViewDelegate
,因为我想在用户滚动时做一些动画。问题是:
如何将滚动视图添加到现有视图?
我在我的ViewController
:
@IBOutlet var container: UIView! // "container" is all of "Safe Area"
var profile = <Some object that's not nil>
override func viewDidLoad() {
super.viewDidLoad()
container.addSubview(ProfileView(frame: container.frame, profile: profile))
print("\(container.subviews.debugDescription)")
}
但滚动视图未显示,“print”语句打印:
[
<_UILayoutGuide: 0x7fca15107cf0; frame = (0 0; 0 0); hidden = YES; layer = <CALayer: 0x60c00003a1c0>>,
<_UILayoutGuide: 0x7fca1510eb60; frame = (0 0; 0 0); hidden = YES; layer = <CALayer: 0x60c000037260>>,
<TestApp.ProfileView: 0x7fca151031e0; frame = (0 0; 414 736); layer = <CALayer: 0x60c000036fc0>>
]
答案 0 :(得分:1)
你说&#34;但滚动视图未显示&#34;。这很容易理解;它是因为你从未表现出来。
查看您的ProfileView
课程代码。它声明了一个profileScrollView
,它是一个滚动视图,并给它一个框架,并给它一个委托,但它永远不会将该滚动视图放入界面。您将ProfileView本身添加到界面,但您从未将ProfileView的profileScrollView
添加到界面。
某处,某种程度上,您需要在addSubview(profileScrollView)
的接口中告诉某些视图 。但你永远不会这样做。