Error: Multiple inheritance from classes 'UICollectionViewController' and 'UICollectionViewLayout' - ios

In Xcode 8 I'm trying to make a subclass of UICollectionViewController and UICollectionViewLayout but I get the error:
Multiple inheritance from classes 'UICollectionViewController' and 'UICollectionViewLayout'
but they have different parents classes. I'm trying to follow http://nshint.io/blog/2015/07/16/uicollectionviews-now-have-easy-reordering/ tutorial for reorder custom size cells
class WordCollectionViewController: UICollectionViewController, UICollectionViewLayout {
// ...
override func invalidationContext(forInteractivelyMovingItems targetIndexPaths: [IndexPath], withTargetPosition targetPosition: CGPoint, previousIndexPaths: [IndexPath], previousPosition: CGPoint) -> UICollectionViewLayoutInvalidationContext {
var context = super.invalidationContext(forInteractivelyMovingItems: targetIndexPaths, withTargetPosition: targetPosition, previousIndexPaths: previousIndexPaths, previousPosition: previousPosition)
return context
}
}

Beyond my comment. Swift DOES NOT support multiple inheritances. UICollectionViewLayout is a class, so since your WorldCollectionViewController is already inheriting from UICollectionViewController you cannot inherit from UICollectionViewLayout (you also don't want to). This:
class ViewController: UIViewController, UITextFieldDelegate {
}
is not multiple inheritances but a single inheritance from the UIViewController and conformance to a protocol UITextFieldDelegate.
You can read more about what protocols are and how to use them here: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html
Essentially protocols are like a set of guidelines. These guidelines specify methods and properties. If a class conforms to a protocol then it must implement the methods and properties described in the protocol's guidelines. For example:
protocol hasAVariablePotato {
var potato: String! { get set }
}
Any object that conforms to this protocol must have a variable (not a let constant) potato that is of type String and implicitly unwrapped. Like so:
class PotatoFarmer: Farmer, hasAVariablePotato {
}
The above PotatoFarmer class inherits from a Farmer class and but does not conform to hasAVariablePotato because there is no potato var! So the above will generate the error:
Type 'PotatoFarmer' does not conform to protocol 'hasAVariablePotato'
To fix this error the programmer must add in the properties and methods of the protocol, like so:
class PotatoFarmer: Farmer, hasAVariablePotato {
var potato: String!
}
The error will now disappear because you have conformed to the protocol.
For your situation you want to make separate subclasses of UICollectionViewLayout and UICollectionViewLayoutAttributes. To see how to do this check here (a great FREE tutorial on the subject):
https://www.raywenderlich.com/107439/uicollectionview-custom-layout-tutorial-pinterest

Swift doesn't support multiple inheritances. UICollectionViewController and UICollectionViewLayout both are class. Don't inherit both the class. You can use below code instead
import Foundation
import UIKit
class Test:UICollectionViewLayout{
override func invalidationContext(forInteractivelyMovingItems targetIndexPaths: [IndexPath], withTargetPosition targetPosition: CGPoint, previousIndexPaths: [IndexPath], previousPosition: CGPoint) -> UICollectionViewLayoutInvalidationContext {
var context = super.invalidationContext(forInteractivelyMovingItems: targetIndexPaths, withTargetPosition: targetPosition, previousIndexPaths: previousIndexPaths, previousPosition: previousPosition)
return context
}
}

Related

Override protocol method not implemented in superclass

I have a superclass in a framework that implements an Objective-C protocol with optional methods. The superclass does not implement these optional methods. In the project that uses this framework, I would like to implement these methods in my subclass. However, I'm getting errors from Swift. Is there a better way to do this or a better design in the framework?
Note: Please keep in mind that the SuperClass is in an XCFramework and the SubClass was inside the application where the created XCFramework was imported.
import UIKit
class SuperClass: NSObject, UIScrollViewDelegate {} // This will be inside an XCFramework
class SubClass: SuperClass {
override func scrollViewDidScroll(_ scrollView: UIScrollView) { // Error: Method does not override any method from its superclass
print("test")
}
}

Why does swift hide default implementation for restricted protocols?

I have a protocol which declaration looks like this:
protocol RefreshableView where Self: UIView {
func reload()
}
And it has default implementation which looks as follows:
extension RefreshableView {
func reload() {
print("Default implementation")
}
}
Then if I declare another (empty) extension of UIView conforming to this protocol I get compile-time error stating that UIView does not conform to the protocol.
extension UIView: RefreshableView {}
It should not be a case from my point of view, as default implementation is provided. However if I remove where statement (restriction to the classes which can conform to the protocol) from declaration of the protocol, everything works as expected. Another option to silence this error is to give the same where statement next to default extension declaration, but it feels redundant as I already let compiler know the protocol is supposed for narrow audience. Is there an explanation to this behavior?
What you're saying is that this doesn't compile:
protocol RefreshableView where Self: UIView {
func reload()
}
extension RefreshableView {
func reload() {
print("Default implementation")
}
}
extension UIView: RefreshableView {
}
As Rob Napier points out in a comment, that's a very odd thing to say, because if UIView itself is going to adopt RefreshableView, then what's the protocol for? The original declaration of the protocol means that only a UIView subclass can adopt RefreshableView, so what the compiler expects is that that's what will happen:
protocol RefreshableView where Self: UIView {
func reload()
}
extension RefreshableView {
func reload() {
print("Default implementation")
}
}
class MyView: UIView {}
extension MyView: RefreshableView {
}
That is a useful real-world case, and it compiles just fine.
So you could file a bug against your original code, but you have to admit it
is a very peculiar edge case to start with; you are saying something that no one would in fact ever say.

View Controller only Protocol has no access to View Controller properties

I have a UIViewController only protocol
protocol VCProtocol where Self: UIViewController {}
I have a function with VCProtocol parameter. Inside the function I can not access any property of UIViewController
func testFunction(vcProtocol: VCProtocol) {
// vcProtocol.view ‼️ error: Value of type 'VCProtocol' has no member 'view'
}
Though I can cast the protocol parameter to UIViewController and then access the property like this:
func testFunction(vcProtocol: VCProtocol) {
(vcProtocol as! UIViewController).view
}
Is this is the way? Do we have any better way?
You can use the & operator to combine protocols
protocol VCProtocol where Self: UIViewController {}
func testFunction(vcProtocol: VCProtocol & UIViewController) {
let view = vcProtocol.view
}
It seems like this is now supported properly from Swift 5. You can try it Xcode 10.2 beta 4. For older versions, you would have to resort to #Ricky Mo's solution.
protocol VCProtocol: UIViewController {
func testFunction(vcProtocol: VCProtocol)
}
class A: UIViewController, VCProtocol {
func testFunction(vcProtocol: VCProtocol) {
debugPrint(vcProtocol.view)
}
}
From the notes,
Protocols can now constrain their conforming types to those that
subclass a given class. Two equivalent forms are supported:
protocol MyView: UIView { /*...*/ }
protocol MyView where Self: UIView { /*...*/ }
Swift 4.2 accepted the second form, but it wasn’t fully implemented
and could sometimes crash at compile time or runtime. (SR-5581)
(38077232)

Swift: How to implement CVCalendar

I am trying to implement the CVCalendar cocoapod (https://github.com/Mozharovsky/CVCalendar) and in the instructions it says:
'CVCalendar requires an implementation of two protocols CVCalendarViewDelegate and CVCalendarMenuViewDelegate, please implement both.'
I dont understand how to go about doing this.
You just need to make your class a subclass of CVCalendarViewDelegate and CVCalendarMenuViewDelegate.
class ViewController: UIViewController, CVCalendarViewDelegate, CVCalendarMenuViewDelegate {
Documentation: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Inheritance.html#//apple_ref/doc/uid/TP40014097-CH17-ID195
Take a look at the answer to this question: Conform to protocol in ViewController, in Swift
As per Oliver's answer you need to add protocols to your class declaration :
class ViewController: UIViewController,CVCalendarMenuViewDelegate,CVCalendarViewDelegate {
You also need to add these two functions to comply with the new protocols:
func presentationMode() -> CalendarMode{
return .monthView
}
func firstWeekday() -> Weekday{
return .monday
}

Overriding delegate property of UIScrollView in Swift (like UICollectionView does)

UIScrollView has a delegate property which conforms to UIScrollViewDelegate
protocol UIScrollViewDelegate : NSObjectProtocol {
//...
}
class UIScrollView : UIView, NSCoding {
unowned(unsafe) var delegate: UIScrollViewDelegate?
//...
}
UICollectionView overrides this property with a different type UICollectionViewDelegate
protocol UICollectionViewDelegate : UIScrollViewDelegate, NSObjectProtocol {
//...
}
class UICollectionView : UIScrollView {
unowned(unsafe) var delegate: UICollectionViewDelegate?
//...
}
When I try to override UIScrollViews delegate with my protocol like so:
protocol MyScrollViewDelegate : UIScrollViewDelegate, NSObjectProtocol {
//...
}
class MyScrollView: UIScrollView {
unowned(unsafe) var delegate: MyScrollViewDelegate?
}
the compiler gives me two warnings:
Property 'delegate' with type 'MyScrollViewDelegate?' cannot override a property with type 'UIScrollViewDelegate?'
'unowned' cannot be applied to non-class type 'MyScrollViewDelegate?'
How can I subclass UIScrollView and override type of delegate property (i.e. use a custom delegate protocol) ?
I think overriding an inherited property is something that's possible in Objective-C but not (at least currently) in Swift. The way I've handled this is to declare a separate delegate as a computed property of the correct type that gets and sets the actual delegate:
#objc protocol MyScrollViewDelegate : UIScrollViewDelegate, NSObjectProtocol {
func myHeight() -> CGFloat
// ...
}
class MyScrollView: UIScrollView {
var myDelegate: MyScrollViewDelegate? {
get { return self.delegate as? MyScrollViewDelegate }
set { self.delegate = newValue }
}
}
This way anything that calls the scroll view delegate normally still works, and you can call your particular delegate methods on self.myDelegate, like this:
if let height = self.myDelegate?.myHeight() {
// ...
}
You can do like this:
protocol ExtendedUIScrollViewDelegate: UIScrollViewDelegate {
func someNewFunction()
}
class CustomScrollView: UIScrollView {
weak var myDelegate: ExtendedScrollViewDelegate?
override weak var delegate: UIScrollViewDelegate? {
didSet {
myDelegate = delegate as? ExtendedScrollViewDelegate
}
}
}
Hope this helps
My favoured method personally is not to subclass scrollviews directly but to make a UIView subclass containing and acting as delegate for a separate scrollview, then forward that scrollview's delegate messages on to the UIView subclass's own delegate where necessary. This also allows for the adding of custom controls outside of the area defined by the scroll view. It may seem a little inelegant compared to a direct subclass, but it does at least avoid unpleasant hacks.
Here is a solution for changing the type of the overriding properties in Swift. It is especially useful when you need to extend protocols of delegates.
#objc protocol ExtendedUIScrollViewDelegate: UIScrollViewDelegate {
func someNewFunction()
}
class CustomScrollView: UIScrollView {
weak var delegateInterceptor: ExtendedScrollViewDelegate?
override var delegate: UIScrollViewDelegate! {
didSet {
if let newValue = delegate {
let castedDelegate = unsafeBitCast(delegate, ExtendedScrollViewDelegate.self)
delegateInterceptor = castedDelegate
}
else {
delegateInterceptor = nil
}
}
}
}
This works as tested with Swift version 1.2. I hope it helps.
You can override get and set method by declare function like:
func setDelegate(delegate:UITableViewDelegate?){
self.delegateInterceptor = delegate;
}
swift compiler the property to method as Objective-c does.
Consider the following situation:
class BaseProp {}
class Base {
var prop: BaseProp
}
Then if you do this:
class DerivedProp: BaseProp {}
class Derived: Base {
override var prop: DerivedProp
}
Then if would break the subclassing principles (namely, the Liskov Substitution Principle). Basically what you are doing is limiting the scope of "var prop" from wider "BaseProp" type to a more narrow "DerivedProp" type. Then this kind of code would be possible, which does not make sense:
class UnrelatedProp: BaseProp {}
let derived = Derived()
let base = derived as Base
base.prop = UnrelatedProp()
Note that we are assigning an instance of UnrelatedProp to the property, which does not make sense for the Derived instance which we actually operate with. ObjectiveC allows such kind of ambiguity, but Swift doesn't.

Resources