papi_douchy
papi_douchy

Reputation: 35

trying to add a textfield into an nsmenuitem but it wont show up

here is the code i use to try to add a textfield into an nsmenuitem

class menuitemtest1: NSTextField {
  var menuitemtest1 = NSTextField()
  override func viewDidChangeBackingProperties() {
    menuitemtest1.frame = CGRect(x: 220, y: 8, width: 103, height: 17)
    menuitemtest1.stringValue = "Maximum Lenght"
    menuitemtest1.isEditable = false
    menuitemtest1.textColor = .gray
    menuitemtest1.isSelectable = false
    menuitemtest1.drawsBackground = false
 }
}

thats the class and how i add it

    var textFieldInMenutest = NSMenuItem()
    menuBarMenu.addItem(textFieldInMenutest)
    textFieldInMenutest.view = menuitemtest1()

Upvotes: 1

Views: 230

Answers (1)

seth
seth

Reputation: 1708

You created an NSTextField subclass which has as a property, a separate and direct NSTextField instance. This makes no sense. What you intended to do, was this:

class menuitemtest1: NSTextField {
  override func viewDidChangeBackingProperties() {
    self.frame = CGRect(x: 220, y: 8, width: 103, height: 17)
    self.stringValue = "Maximum Lenght"
    self.isEditable = false
    self.textColor = .gray
    self.isSelectable = false
    self.drawsBackground = false
 }
}

As for why it "doesn't show up" — the text field you did add as the menu item's view has a zero-sized (default) frame, so it's simply invisible.

Further, viewDidChangeBackingProperties is not the correct place to set up basic properties of the field. In such a subclass, you should use the initializer, init(frame:... or init(coder: ...

Upvotes: 1

Related Questions