问题
Having written a UIPrintInteractionControllerDelegate
, I wish to unit test its paper selection functionality in printInteractionController:choosePaper:
Its declaration is:
optional func printInteractionController(_ printInteractionController: UIPrintInteractionController, choosePaper paperList: [UIPrintPaper]) -> UIPrintPaper
It is a simple matter of calling it with predefined UIPrintPaper values and checking the output. However I am unable to create UIPrintPaper instances. Here is how UIPrintPaper is declared:
NS_CLASS_AVAILABLE_IOS(4_2)__TVOS_PROHIBITED @interface UIPrintPaper : NSObject
+ (UIPrintPaper *)bestPaperForPageSize:(CGSize)contentSize withPapersFromArray:(NSArray<UIPrintPaper *> *)paperList; // for use by delegate. pass in list
@property(readonly) CGSize paperSize;
@property(readonly) CGRect printableRect;
@end
The paperSize and printableRect properties are readonly and there is no initializer to define them. How can I create UIPrintPaper to represent different paper sizes for my tests? (A4, US Letter, 4x6...)
回答1:
Can't control UIPrintPaper, but subclassing it to override its readonly properties is straighforward:
class FakePrintPaper: UIPrintPaper {
private let size: CGSize
override var paperSize: CGSize { return size }
override var printableRect: CGRect { return CGRect(origin: CGPointZero, size: size) }
init(size: CGSize) {
self.size = size
}
}
回答2:
Use the UIPrintPaper
class method bestPaperForPageSize
:
let paper = UIPrintPaper.bestPaperForPageSize(CGSize(...), withPapersFromArray: [...])
I imagine you would want to use it like this:
class MyClass: NSObject { }
extension MyClass: UIPrintInteractionControllerDelegate {
func printInteractionController(printInteractionController: UIPrintInteractionController, choosePaper paperList: [UIPrintPaper]) -> UIPrintPaper {
return UIPrintPaper.bestPaperForPageSize(CGSize(...), withPapersFromArray: paperList)
}
}
Where CGSize is your paper size.
回答3:
I don't think you are supposed to create UIPrintPaper. The Apple API calls:
- (UIPrintPaper*)printInteractionController:(UIPrintInteractionController *)printInteractionController choosePaper:(NSArray<UIPrintPaper *> *)paperList
... on your UIPrintInteractionControllerDelegate with an array of all UIPaper supported by your printer. If you don't get the one you want, then the printer doesn't support it.
So instead of creating one, implement this delegate call, and return the correct UIPrintPaper from the params that the printer supports.
来源:https://stackoverflow.com/questions/37551043/how-to-create-a-uiprintpaper-to-test-uiprintinteractioncontrollerdelegate