我有一个UICollectionView
子类。
我想为scrollViewDidScroll
中的UIScrollViewDelegate
添加默认实现
是否可以从UICollectionView
子类访问scrollView委托方法?
谢谢
答案 0 :(得分:1)
您可以添加一个实现所需默认代码的函数,例如:
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
//...
}
}
答案 1 :(得分:0)
我们可以使用delegation
概念从用户CustomCollectionView
进行滚动访问。
这是CustomCollectionView
的实现,还请注意,delegate
中可用的optional
方法是Objective C
。
因此,如果您的ViewController
确认CustomCollectionViewDelegate
protocol
,则它需要实现委托方法,而不必这样做。
注意:
但是,CustomCollectionView
是UICollectionView
的子类,表示其简单的通用UI元素。实际上,它是View
中的Model-View-Controller (MVC)
。根据{{1}},MVC
无法直接与View
通话,Controller
和View
之间的通信为Controller
。此类通信的好例子是blind & structured
和Target & Action
模式。
委托是一个简单的变量,包含在通用delegate
等通用UI组件中。UIScrollView, UITableView, UICollectionView
必须通过设置UI元素的Controller
来确认协议到delegate
来实现其中的委托方法。
结论是通用UI元素的子类无法在其中实现委托方法。
但是,我们可以通过使用self
创建自定义的UIView
并将其添加XIB
来实现。
代码:
CustomCollectionView:
collectionView
CustomCollectionView XIB:
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
}
}
ViewController:
<?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>
委托实施:
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)
}