19

我正在创建可可应用程序,我在其中以这样的方式创建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];  

现在我想要我的文本垂直对齐,它应该可以根据文本长度进行调整。
有人有什么建议吗?请分享您的建议:)

非常感谢..!!

4

4 回答 4

13

你想要什么是可能的,但你必须创建一个 NSTextFieldCell 的子类,然后在你的 NSTextField 中使用该子类。您想要覆盖的关键方法是drawingRectForBounds:selectWithFrame:editWithFrame:

这是来自出色的 Daniel Jalkut 的一篇关于此的博客文章,他甚至包括一个可供下载的版本。该帖子相当旧,但它应该仍然可以正常工作。

于 2012-04-18T08:11:34.030 回答
1

为了将文本字段调整为字符串大小,您必须使用NSString's来计算文本大小,sizeWithFont: constrainedToSize: lineBreakMode:然后通过设置框架来调整文本字段的大小。

对于垂直对齐看这个问题(和答案)。

于 2012-04-18T08:04:59.353 回答
0

这是上面sosborn链接到的解决方案的 Swift 版本:

open class VerticallyCenteredTextFieldCell: NSTextFieldCell {
    
    fileprivate var isEditingOrSelecting : Bool = false
    
    open override func drawingRect(forBounds rect: NSRect) -> NSRect {
        let rect = super.drawingRect(forBounds: rect)
        
        if !isEditingOrSelecting {
            let size = cellSize(forBounds: rect)
            return NSRect(x: rect.minX, y: rect.minY + (rect.height - size.height) / 2, width: rect.width, height: size.height)
        }
        
        return rect
    }
    
    open override func select(withFrame rect: NSRect, in controlView: NSView, editor textObj: NSText, delegate: Any?, start selStart: Int, length selLength: Int) {
        let aRect = self.drawingRect(forBounds: rect)
        isEditingOrSelecting = true
        super.select(withFrame: aRect, in: controlView, editor: textObj, delegate: delegate, start: selStart, length: selLength)
        isEditingOrSelecting = false
    }
    
    open override func edit(withFrame rect: NSRect, in controlView: NSView, editor textObj: NSText, delegate: Any?, event: NSEvent?) {
        let aRect = self.drawingRect(forBounds: rect)
        isEditingOrSelecting = true
        super.edit(withFrame: aRect, in: controlView, editor: textObj, delegate: delegate, event: event)
        isEditingOrSelecting = false
    }
    
}
于 2021-08-27T11:46:15.910 回答
-1

此时覆盖 ViewWillDraw 并将您的 NSTextField 放置在其父视图的中心。这也适用于实时调整大小。此时您还可以调整字体大小以找到适合新大小的字体。

于 2015-10-16T22:35:32.977 回答