我有一个UICollectionView子类。
我想为scrollViewDidScroll添加一个来自UIScrollViewDelegate的默认实现
有办法从scrollView子类访问UICollectionView委托方法吗?
谢谢
发布于 2018-11-11 00:15:01
可以添加实现所需默认代码的函数,例如:
class YourCollectionView: UICollectionView {
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func updateUIOnScrollViewDidScroll(_ scrollView: UIScrollView) {
//...
}
}然后,在视图控制器中实现委托函数时,添加:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
yourCollectionView.updateUIOnScrollViewDidScroll(scrollView)
}编辑
如果您想像使用外部库一样使用您的集合,并且不希望每次调用更新的函数,则可以实现一个只符合UICollectionViewDelegate的自定义类(如果您想要的话,也可以有一个单独的CustomDataSource类来实现数据源和委托),例如:
class YourCollectionViewDelegate: NSObject, UICollectionViewDelegate {
// implement a callback for every function you need to manage in the view controller
var onSelectedItemAt: ((IndexPath) -> Void)?
func collectionView(_ collectionView: UICollectionView,
didSelectItemAt indexPath: IndexPath)
onSelectedItemAt?(indexPath)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard let collectionView = scrollView as? YourCollectionViewClass else { fatalError(“your message”) }
// implement your ui update
}然后,在视图控制器中,只需将委托与视图控制器绑定:
class MyViewController: UIViewController {
//...
let customDelegate = YourCollectionViewDelegate()
override func viewDidLoad() {
super.viewDidLoad()
//...
myCollection.delegate = customDelegate
setupBindings()
}
private func setupBindings() {
customDelegate.onSelectedItemAt = { [weak self] indexPath in
//...
}
}发布于 2018-11-11 08:25:30
只要用户滚动,我们就可以使用delegation概念从CustomCollectionView获得访问。
这是CustomCollectionView的实现,请注意,delegate方法是optional,在Objective C中是可用的。
这样,如果您的ViewController确认到CustomCollectionViewDelegate protocol,那么它就需要实现它不必实现的委托方法。
注:
然而,CustomCollectionView是UICollectionView的子类,意味着它的简单通用UI元素。实际上,它是View In Model-View-Controller (MVC)。根据MVC,View不能直接与Controller通信,View与Controller之间的通信是blind & structured。这种通信的好例子是Target & Action和delegate模式。
委托是一个简单的变量,包含在通用UI组件(如UIScrollView, UITableView, UICollectionView等)中。Controller必须通过将UI元素的delegate设置为self来确认协议,以便在其中实现委托方法。
结论是泛型UI元素的子类不能在其中实现委托方法。
但是,我们可以通过使用UIView制作一个定制的XIB并将collectionView添加到其中来实现这一点。
代码:
CustomCollectionView:
import UIKit
@objc protocol CustomCollectionViewDelegate {
@objc optional func collectionViewDidScroll(_ scrollView: UIScrollView)
}
class CustomCollectionView: UIView {
//MARK: - Outlets
@IBOutlet weak var collection: UICollectionView!
//MARK: - Variables
weak var vc: UIViewController!
weak var view: UIView!
weak var customDelegate: CustomCollectionViewDelegate?
let titles = ["HorizontalCollectionView", "VerticalCollectionView"]
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(frame: CGRect, in vc: UIViewController, setCustomDelegate set: Bool) {
super.init(frame: frame)
xibSetup(frame: CGRect(x: 0, y: 0, width: frame.width, height: frame.height))
self.vc = vc
self.customDelegate = set ? vc as? CustomCollectionViewDelegate : nil
}
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup(frame: CGRect(x: 0, y: 0, width: frame.width, height: frame.height))
}
private func xibSetup(frame: CGRect) {
view = loadViewFromNib()
view.frame = frame
addSubview(view)
collection.register(UINib(nibName: "CustomCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CustomCollectionViewCell")
collection.delegate = self
collection.dataSource = self
}
private func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "CustomCollectionView", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
return view
}
}
extension CustomCollectionView: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if customDelegate != nil {
customDelegate!.collectionViewDidScroll!(scrollView)
}
}
}
extension CustomCollectionView: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return titles.count
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 10 // Adjust the inter item space based on the requirement.
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 300, height: collectionView.bounds.height)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCollectionViewCell", for: indexPath) as! CustomCollectionViewCell
cell.titleLabel.text = titles[indexPath.row]
return cell
}
}CustomCollectionView XIB:
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="14313.18" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14283.14"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="CustomCollectionView" customModule="SampleDemoApp" customModuleProvider="target">
<connections>
<outlet property="collection" destination="loF-CI-n5C" id="EZi-It-39z"/>
</connections>
</placeholder>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view contentMode="scaleToFill" id="iN0-l3-epB" customClass="CustomCollectionView" customModule="SampleDemoApp" customModuleProvider="target">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<collectionView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" dataMode="none" translatesAutoresizingMaskIntoConstraints="NO" id="loF-CI-n5C">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
<collectionViewFlowLayout key="collectionViewLayout" scrollDirection="horizontal" minimumLineSpacing="10" minimumInteritemSpacing="10" id="HQB-uW-7CY">
<size key="itemSize" width="50" height="50"/>
<size key="headerReferenceSize" width="0.0" height="0.0"/>
<size key="footerReferenceSize" width="0.0" height="0.0"/>
<inset key="sectionInset" minX="0.0" minY="0.0" maxX="0.0" maxY="0.0"/>
</collectionViewFlowLayout>
</collectionView>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="loF-CI-n5C" firstAttribute="top" secondItem="iN0-l3-epB" secondAttribute="top" id="Khs-Aw-6b7"/>
<constraint firstItem="loF-CI-n5C" firstAttribute="leading" secondItem="vUN-kp-3ea" secondAttribute="leading" id="cEr-al-Pib"/>
<constraint firstItem="vUN-kp-3ea" firstAttribute="bottom" secondItem="loF-CI-n5C" secondAttribute="bottom" id="ftp-QG-OGJ"/>
<constraint firstItem="vUN-kp-3ea" firstAttribute="trailing" secondItem="loF-CI-n5C" secondAttribute="trailing" id="num-9n-spN"/>
</constraints>
<viewLayoutGuide key="safeArea" id="vUN-kp-3ea"/>
<point key="canvasLocation" x="138.40000000000001" y="153.37331334332833"/>
</view>
</objects>
</document>ViewController:
override func viewDidLoad() {
super.viewDidLoad()
let collectionView = CustomCollectionView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 200), in: self, setCustomDelegate: true)
view.addSubview(collectionView)
}代理实现:
extension ViewController: CustomCollectionViewDelegate {
func collectionViewDidScroll(_ scrollView: UIScrollView) {
//do something...
}
}https://stackoverflow.com/questions/53244392
复制相似问题