简体   繁体   中英

How can I get an NSTextField to behave like a HTML text?

I have some static text that is usually only 1 line long that displays in a NSTextField in my xib. In some instances, the text is long enough to warrant 2 lines, and I just want the label to resize vertically to fit it, without giving me scrollers or any thing else. Think of how text on a webpage behaves… that is what I want. I just want the label to grow shrink with different text, and with adjustments to its width. How can I achieve this?



UPDATE
Here is a video of how it currently behaves: http://screencast.com/t/4JYTv7jVG3O

Notice how when the NSTextField is two lines long, there is a big gap underneath the text. This is because the stars and button are aligned at the bottom of the frame, and because I have to have the frame taller to accommodate 2 lines, they stay there. If I can get an answer to this question, I would make the frame shorter for the 1 line text, and make the bottom textfield (with the smaller text) taller to compensate. Can this type of floating layout be done?

One option is to actually use a WebView to display your content. You will then get exactly the behaviour you are expecting, at the cost of a bit of work to manage interaction with the controls.

You would need to set the WebView to display no background, using [webView setDrawsBackground:NO] .

You'd also need to construct the content (including the star rating and the button) using HTML/CSS and then use the Objective-C/JavaScript bridge to call back to your app when the button is pressed.

More information on calling Objective-C from JavaScript is here .

You could probably also use an NSTextView and embed the button and star rating as NSTextAttachment objects but this is quite complex, it would be a lot easier to use a WebView .

The only other alternative that I can see is writing a view controller that manages the layout of the controls based on the current size of their container view. You would need to measure the text to do this and one way to do that is to use the excellent NS(Attributed)String+Geometrics category written by Jerry Krinock.

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