Cocoa:如何制作多行的NSTextField?

14

如何创建多行的NSTextField?更新:我在IB中发现了一种特殊类型的NSTextField,称为“Wrapped Text Field”。它是多行的,但当我想要换行时,我必须按Ctrl+Enter。但我只想按Enter键换行。我该怎么做?


6
你不能只使用NSTextView吗?它是一个多行文本框。 - Asher Dunn
你可以查看我的答案,以获取使用自动约束的另一种解决方案。https://dev59.com/epfga4cB1Zd3GeqPBdAh#48705158 - abdullahselek
3个回答

15

在Interface Builder中无法单独指定此行为。您可以通过代理消息来完成,如此技术说明书QA1454所述。

这是技术说明书中的示例代理消息:

- (BOOL)control:(NSControl*)control textView:(NSTextView*)textView doCommandBySelector:(SEL)commandSelector
{
    BOOL result = NO;

    if (commandSelector == @selector(insertNewline:))
    {
        // new line action:
        // always insert a line-break character and don’t cause the receiver to end editing
        [textView insertNewlineIgnoringFieldEditor:self];
        result = YES;
    }
    else if (commandSelector == @selector(insertTab:))
    {
        // tab action:
        // always insert a tab character and don’t cause the receiver to end editing
        [textView insertTabIgnoringFieldEditor:self];
        result = YES;
    }

    return result;
}

6

使用NSTextView,它类似于多行文本框NSTextField,它是NSText的一个子类。如果我有误,请纠正。 NSTextView有一个NSTextStorage,它是NSAttributedString的子类。您需要提供一个NSAttributedString对象来填充其内容,而不是NSString,因为它可以显示颜色等。

[[yourTextView textStorage] setAttributedString:attrStr];

0
与Jon Steinmetz的答案相同,但适用于Swift:
func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
        if commandSelector == #selector(NSControl.insertNewline)
        {
            // new line action:
            // always insert a line-break character and don’t cause the receiver to end editing
            textView.insertNewlineIgnoringFieldEditor(self)
            return true
        }
        else if commandSelector == #selector(NSControl.insertTab)
        {
            // tab action:
            // always insert a tab character and don’t cause the receiver to end editing
            textView.insertTabIgnoringFieldEditor(self)
            return true
        }

        return false
    }

我设置的委托协议是 NSTextFieldDelegate

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接