通过使用委托协议,我尝试将一个字符串(inputFromUser.string)从NSViewController-mainController传递给nspoover-lisadmapview的NSView的自定义子类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()
}
}
最佳答案
好吧,有一些架构错误。您根本不需要委托方法和协议。您只需要定义良好的setter方法:
把你的PlasmidMapView
放入NSViewController
子类。此视图控制器必须设置为contentViewController
-控件的属性。不要忘记在NSPopover
-方法或其他方法中按需要设置它。
class PlasmidMapController : NSViewController {
weak var mapView: PlacmidMapView!
}
二。在您的
viewDidLoad
中,不要忘记调用PlacmidMapView
-method onneedsDisplay
设置:class PlasmidMapView: NSView {
//...
var dnaForMap = String() {
didSet {
needsDisplay()
}
//...
}
III.根据需要从
dna
-类中设置dna
-string。@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")
}
}
关于swift - 如何将值从NSViewController传递到NSPopover的自定义NSView?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37204073/