通过使用委托协议,我试图将一个字符串( inputFromUser.string )从NSViewController - mainController 传递给NSPopover的NSView的自定义子类 - PlasmidMapView ,to drawRect函数,请参阅下面的代码。但是,它没有用。我不知道哪里出错。也许还有另一种传递这个字符串的方法。
更新
文件1。
protocol PlasmidMapDelegate {
func giveDataForPLasmidMap(dna: String)
}
class MainController: NSViewController {
@IBOutlet var inputFromUser: NSTextView!
var delegate: plasmidMapDelegate?
@IBAction func actionPopoverPlasmidMap(sender: AnyObject) {
popoverPlasmidMap.showRelativeToRect(sender.bounds,
ofView: sender as! NSView, preferredEdge: NSRectEdge.MinY)
let dna = inputDnaFromUser.string
delegate?.giveDataForPLasmidMap(dna!)
}
}
文件2
class PlasmidMapView: NSView, PlasmidMapDelegate {
var dnaForMap = String()
func giveDataForPLasmidMap(dna: String) {
dnaForMap = dna
}
override func drawRect(dirtyRect: NSRect) {
let objectOfMainController = MainController()
objectOfMainController.delegate = self
//here I have checked if the string dnaForMap is passed
let lengthOfString = CGFloat(dnaForMap.characters.count / 10)
let pathRect = NSInsetRect(self.bounds, 10, 45)
let path = NSBezierPath(roundedRect: pathRect,
xRadius: 5, yRadius: 5)
path.lineWidth = lengthOfString //the thickness of the line should vary in dependence on the number of typed letter in the NSTextView window - inputDnaFromUser
NSColor.lightGrayColor().setStroke()
path.stroke()
}
}
答案 0 :(得分:1)
为了使用委托你的类 PlasmidMapView 需要有一个 MainController 的实例(btw名称约定是Class,而不是class)并且符合 PlasmidMapDelegate (名称惯例再次规定它应该是PlasmidMapDelegate)。通过该实例,您可以:
mainController.delegate = self
答案 1 :(得分:1)
好的,有一些架构错误。您根本不需要委托方法和协议。您只需要明确定义的setter方法:
予。将PlasmidMapView
放入NSViewController
- 子类。此视图控制器必须设置为contentViewController
- NSPopover
- 控件的属性。不要忘记在viewDidLoad
- 方法或其他方法中按照您需要的方式设置它。
class PlasmidMapController : NSViewController {
weak var mapView: PlacmidMapView!
}
II。在PlacmidMapView
忘记致电needsDisplay
时,dna
上的方法确实设置了:
class PlasmidMapView: NSView {
//...
var dnaForMap = String() {
didSet {
needsDisplay()
}
//...
}
III。只要您需要dna
课程,请设置MainController
- 字符串。
@IBAction func actionPopoverPlasmidMap(sender: AnyObject) {
popoverPlasmidMap.showRelativeToRect(sender.bounds,
ofView: sender as! NSView, preferredEdge: NSRectEdge.MinY)
let dna = inputDnaFromUser.string
if let controller = popoverPlasmidMap.contentViewController as? PlasmidMapController {
controller.mapView.dna = dna
} else {
fatalError("Invalid popover content view controller")
}
}
答案 2 :(得分:1)
所以,几天之后我找到了一个没有任何协议和授权的解决方案,正如Astoria所提到的那样。我需要做的就是在 MainController 类中为我的自定义NSView创建@IBOutlet var plasmidMapIBOutlet: PlasmidMapView!
,然后使用它在{{{}中设置 dnaForMap 的值1}}。
@IBAction func actionPopoverPlasmidMap(sender: AnyObject)