2

I work with Xcode5.

I would like the width of my NSTextField to adapt to its content.

If possible, I would like to do this in InterfaceBuilder and if possible, without subclassing.

EDIT : I am working with autolayout ON !! (which seems to prevent me from changing the width of my NSTextField)

Colas
  • 3,473
  • 4
  • 29
  • 68
  • 1
    why is it that you need this? I may be able to give an alternate solution that could assists you, or at least help to point you in the right direction. – A'sa Dickens Sep 27 '13 at 13:03
  • I have a generic label : "Hello ". After this label, I have another `NSTextView`. I want the second one to be right after the first one. – Colas Sep 27 '13 at 13:15
  • 1
    I am not an auto layout expert, but it works with weights, so can't you assign a stronger weight to content fit than right edge? – Grady Player Sep 27 '13 at 20:05

3 Answers3

5

Try like this:- connect delegate to your textfield

-(void)controlTextDidChange:(NSNotification *)obj
{
    NSString *str=[yourTextField stringValue];
    NSCell *cell=[[NSCell alloc]initTextCell:str];
    CGFloat sz=[cell cellSize].width;
    [yourTextField setFrameSize:NSMakeSize(sz+10.0, 22.0)];
}
Hussain Shabbir
  • 14,801
  • 5
  • 40
  • 56
  • It works if `autolayout` is not active. But it doesn't work with `autolayout` ON... And I need `autolayout` ! – Colas Sep 27 '13 at 13:20
  • 1
    Autolayout has a constraint called "intrinsic value" which means to set the label to the size of it's content. This is only for a UILabel so you can't type in it... – A'sa Dickens Sep 27 '13 at 18:23
2

In the documentation for a NSTextField there is nothing that shows that a NSTextField can resize depending on its content, so with that I assume it's impossible. For the kicks and giggles, though, I checked the storyboard and there is no property that allows your NSTextField to be resized besides the auto resizing mask, which have nothing to do with the NSTextField text attribute.

NSGod
  • 22,699
  • 3
  • 58
  • 66
A'sa Dickens
  • 2,045
  • 1
  • 16
  • 21
  • Why is this the accepted answer? This is obviously not impossible and there are multiple ways you could choose to tackle this problem. `boundingRect(with size: NSSize, options: NSStringDrawingOptions = [], attributes: [String : Any]? = nil) -> NSRect` on `NSString` is one method you could start with. – Charlton Provatas Sep 16 '17 at 20:29
  • When crafting the answer above, I was under the assumption that they wanted a no overhead approach such as resizing to intrinsic size. Autolayout is nothing more than a bunch of math calculations that you can always do yourself if you desire and with that logic everything is re-sizable. – A'sa Dickens Sep 18 '17 at 01:50
1

Try to set the preferredMaxLayoutWidth for NSTextfield, this value will be used to update your height, I hope it is helpful. And Reference resources:UILabel sizeToFit doesn't work with autolayout ios6

Jeric
  • 11
  • 1