简体   繁体   中英

How to resize NSTextField when content increase in NSTextField

i have NSTextField but content that i have to show is not fixed , it will grow dynamically. is there any way in simple way through which we can change size dynamically. Thanks in Advance :)

The text field's delegate needs to update the size as the text changes.

The trick is you have to manually update the stringValue property, to avoid bugs:

override func controlTextDidChange(obj: NSNotification) {
  guard let field = obj.object as? NSTextField else {
    return
  }

  // re-apply the string value, this is necessary for the text field to correctly calculate it's width
  field.stringValue = field.stringValue

  // calculate the new dimensions
  let maxWidth: CGFloat = 500
  let maxHeight: CGFloat = 50
  let size = renameField.sizeThatFits(NSSize(width: maxWidth, height: maxHeight))

  // apply them
  field.frame = NSRect(x: field.frame.origin.x, y: field.frame.origin.y, width: size.width, height: size.height)
}

If you're just showing content, as opposed to typing in the text field, then you should use a label, which can be set in IB to "Size To Fit Content". This will cause the label to be just big enough for the content.

There is no option to set through Interface Builder.

However you can do through codes: You can set a delegate on the NSTextField which implements

- (void)controlTextDidChange:(NSNotification *)aNotification;

Every time the delegate gets called resize the control per your idea above.

Also, this one.

There is a great category on NSString/NSAttributedString by Jerry Krinock which allows you to calculate the height of text based on its width and vice versa:

http://www.sheepsystems.com/sourceCode/sourceStringGeometrics.html

Edit March 2016 :

Now as Autolayout feature is there for Mac OS applications that helps to increase and decrease the size of textfield and even NSWindow, so you can use them it very easy to use. Just put constraints from either side of the Window, and set the constraints something as ( >= desiredMinimumSize ) and you are done!

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