xcode NSTextField 垂直对齐
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10205088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NSTextField Vertical alignment
提问by iUser
I am creating cocoa app in which i created NSTextField
programmatically like this,
我正在创建可可应用程序,我在其中以NSTextField
编程方式创建,
NSView *superView = [[NSView alloc] initWithFrame:NSMakeRect(0, 300, 1400, 500)];
NSTextField *myTextField = [[NSTextField alloc] initWithFrame:NSMakeRect(180, 100, 1000, 300)];
[myTextField setStringValue:myText];
[myTextField setEditable:NO];
[myTextField setBezeled:NO];
[myTextField setDrawsBackground:NO];
[myTextField setSelectable:NO];
[myTextField setFont:[NSFont fontWithName:@"Futura" size:22]];
[superView addSubview:myTextField];
[superView setAutoresizesSubviews:YES];
[myTextField setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
[self.window.contentView addSubview:superView];
Now i want vertical alignment of my text and it should be adjustable according to text length.
Anyone have any suggestions? Please share your suggestion :)
现在我想要我的文本垂直对齐,它应该可以根据文本长度进行调整。
有人有什么建议吗?请分享您的建议:)
Many Thanks..!!
非常感谢..!!
采纳答案by sosborn
What you want is possible, but you'll have to make a subclass of NSTextFieldCell, and then use that subclass in your NSTextField. The key methods you want override are drawingRectForBounds:
, selectWithFrame:
, and editWithFrame:
您想要的是可能的,但您必须创建 NSTextFieldCell 的子类,然后在您的 NSTextField 中使用该子类。你想覆盖的关键方法是drawingRectForBounds:
,selectWithFrame:
和editWithFrame:
Here is a blog post from the fantastic Daniel Jalkutabout this, he even includes a downloadable version ready to go. The post is fairly old but it should still work fine.
这是精彩的 Daniel Jalkut 的一篇关于此的博客文章,他甚至包括一个可供下载的版本。该帖子相当旧,但它应该仍然可以正常工作。
回答by Kai Huppmann
For adjusting the text field to string size you have to calculate the text size with NSString
's sizeWithFont: constrainedToSize: lineBreakMode:
before and than adjust the text field's size with setting the frame.
要将文本字段调整为字符串大小,您必须使用NSString
'ssizeWithFont: constrainedToSize: lineBreakMode:
之前计算文本大小,然后通过设置框架来调整文本字段的大小。
For vertical alignment look at this question(and the answers).
对于垂直对齐,请查看此问题(和答案)。
回答by Radu Simionescu
override ViewWillDraw and position your NSTextField in the center of its parent view at this point. This works with live resizing as well. You can also adjust font size at this point to find a font which fits the new size.
此时覆盖 ViewWillDraw 并将您的 NSTextField 放置在其父视图的中心。这也适用于实时调整大小。此时您还可以调整字体大小以找到适合新大小的字体。