Прокручиваемое поле NSTextField в предупреждающем сообщении - PullRequest
1 голос
/ 06 августа 2020

Я пишу процедуру в swift (Xcode 11.6), которая преобразует текст в формате rtf в структурированный формат под macOS.

Для ввода простого текста я пытаюсь определить текстовое поле, которое является прокручиваются в предупреждающем сообщении и настроили следующую процедуру. К сожалению, предупреждающее сообщение имеет правильный размер, но не отображает текстовое поле «исходный текст». Это сработает, если я определю "исходный текст" как NSTextView (_ frame :) и добавлю его вместо scrollView в качестве вспомогательного элемента к сообщению с предупреждением, но тогда, конечно, его нельзя прокрутить.

Что я делаю не так? Большое спасибо за вашу поддержку

private func readNewText() {
        
        let abfrageNeuerText = NSAlert()
        abfrageNeuerText.alertStyle = .informational
        abfrageNeuerText.messageText = "Input new text"
        abfrageNeuerText.informativeText = ""
        abfrageNeuerText.addButton(withTitle: "Convert")
        abfrageNeuerText.addButton(withTitle: "Cancel")
        
        let scrollView = NSScrollView(frame: NSRect(x:10, y:10, width: 500, height: 700))
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        scrollView.borderType = .noBorder
        scrollView.backgroundColor = NSColor.white
        scrollView.hasVerticalScroller = true
        
        // Initial clip view
        let clipView = NSClipView()
        clipView.translatesAutoresizingMaskIntoConstraints = false
        scrollView.contentView = clipView
        scrollView.addConstraint(NSLayoutConstraint(item: clipView, attribute: .left, relatedBy: .equal, toItem: scrollView, attribute: .left, multiplier: 1.0, constant: 0))
        scrollView.addConstraint(NSLayoutConstraint(item: clipView, attribute: .top, relatedBy: .equal, toItem: scrollView, attribute: .top, multiplier: 1.0, constant: 0))
        scrollView.addConstraint(NSLayoutConstraint(item: clipView, attribute: .right, relatedBy: .equal, toItem: scrollView, attribute: .right, multiplier: 1.0, constant: 0))
        scrollView.addConstraint(NSLayoutConstraint(item: clipView, attribute: .bottom, relatedBy: .equal, toItem: scrollView, attribute: .bottom, multiplier: 1.0, constant: 0))

        // Initial document view
        let originaltext = NSTextView()
        originaltext.translatesAutoresizingMaskIntoConstraints = false
        scrollView.documentView = originaltext
        clipView.addConstraint(NSLayoutConstraint(item: clipView, attribute: .left, relatedBy: .equal, toItem: originaltext, attribute: .left, multiplier: 1.0, constant: 0))
        clipView.addConstraint(NSLayoutConstraint(item: clipView, attribute: .top, relatedBy: .equal, toItem: originaltext, attribute: .top, multiplier: 1.0, constant: 0))
        clipView.addConstraint(NSLayoutConstraint(item: clipView, attribute: .right, relatedBy: .equal, toItem: originaltext, attribute: .right, multiplier: 1.0, constant: 0))
        
        abfrageNeuerText.accessoryView = scrollView
        let response = abfrageNeuerText.runModal()
        switch response {
        case .alertFirstButtonReturn:
            if originaltext.string.count == 0 {
                return
            }
            analyzeNewtext(forText: originaltext.string)
        default: return
        }
    }

1 Ответ

0 голосов
/ 06 августа 2020

Вы усложняете себе автоматическую раскладку. В этом нет необходимости, и всю настройку можно сделать намного короче:

let scrollView = NSScrollView(frame: NSRect(x:0, y:0, width: 200, height: 100))
scrollView.hasVerticalScroller = true

let clipView = NSClipView(frame: scrollView.bounds)
clipView.autoresizingMask = [.width, .height]

let textView = NSTextView(frame: clipView.bounds)
textView.autoresizingMask = [.width, .height]

clipView.documentView = textView
scrollView.contentView = clipView

Проверено на Big Sur:

enter image description here

I can't test it with macOS Catalina right now (got it at another location), but I don't see a reason why it shouldn't work.

Side note - replace count == 0 with isEmpty.

Also check that I do assign textView to clipView.documentView & clipView to scrollView.contentView. It differs from your code.

If you're stuck you can always add Scrollable Text View to some window in the interface builder and inspect all the properties at runtime to learn how it was created and what values are set there.

Full code:

private func readNewText() {
    let alert = NSAlert()
    alert.alertStyle = .informational
    alert.messageText = "Input new text"
    alert.addButton(withTitle: "Convert")
    alert.addButton(withTitle: "Cancel")
    
    let scrollView = NSScrollView(frame: NSRect(x:0, y:0, width: 200, height: 100))
    scrollView.hasVerticalScroller = true
    
    let clipView = NSClipView(frame: scrollView.bounds)
    clipView.autoresizingMask = [.width, .height]
    
    let textView = NSTextView(frame: clipView.bounds)
    textView.autoresizingMask = [.width, .height]
    
    clipView.documentView = textView
    scrollView.contentView = clipView
    
    alert.accessoryView = scrollView
    
    let response = alert.runModal()
    switch response {
    case .alertFirstButtonReturn:
        if textView.string.isEmpty {
            return
        }
        print("analyze: \(textView.string)")
    default: return
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...