简体   繁体   中英

Draw NSTextField setting the content NSRect

Given a struct Concept that has an associated text: String and area: NSRect , that when drawn on the view, it will draw the String in the given NSRect .

I would like to on click, show a NSTextField which "content" (cell) NSRect is equal to the given NSRect

If I tried to set up textField.frame = concept.area , the cell will be rendered in an inset position considering the border + padding of the NSTextField , so it will render the text in a different, slightly moved, NSRect.

In code the idea would be something like

struct Concept {
  let text: String
  let area: NSRect

  func draw() {
    text.draw(inRect: area)
  }
}

let conceptRect = NSRect(x: 50, y: 60, width: 80, height: 20)
let concept = Concept(text: "sample text", area: conceptRect)

let textField = NSTextField()
textField.stringValue = concept.text

textField.???? = area
let textFieldRect = textField.frame

assert(textFieldRect != conceptRect)
assert(textFieldRect.contains(conceptRect))

And the expected result should look like:

在此处输入图片说明

any ideas on how can I achieve this?

thanks

You don't say how you're drawing the string in the area , which can affect exactly where it draws.

If you want to figure out what the text field's border padding is, you can compare its cell 's drawingRect(forBounds:) with the text field's bounds . The drawing rect will be inset by a bit from the bounds. To compute a frame to get a particular drawing rect, you reverse that by "outsetting" from the desired drawing rect by the same amount.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM