macostoolbarappkit

MacOS, AppKit - padding of window title in toolbar


In MacOS app, I have a window created in storyboard, with toolbar style Unified. When launched, the window looks like this:

what window looks like

I need the window title ("General") to have more left padding, in order to be aligned with "Actions" in the window content. How to achieve that?


Solution

  • In the end, I have created a custom NSToolbarItem, that is just text styled the same way as usual window title, but is positioned with required padding

    class ToolbarLabelView : NSView {  
        var label: NSTextField!  
          
        public override init(frame frameRect: NSRect) {  
            super.init(frame: frameRect)  
      
            self.label = NSTextField(labelWithString: "MyLabel")  
            self.label.translatesAutoresizingMaskIntoConstraints = false  
            self.addSubview(self.label)  
              
            self.label.font = NSFont.systemFont(ofSize: 15, weight: .semibold)  
              
            NSLayoutConstraint.activate(\[  
                self.widthAnchor.constraint(equalToConstant: 200),  
      
                self.label.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 105),  
                self.label.centerYAnchor.constraint(equalTo: self.centerYAnchor)  
            \])  
        }  
          
        required init?(coder: NSCoder) {  
            super.init(coder: coder)  
        }  
          
        public func SetLabelText(\_ str: String) {  
            self.label.stringValue = str  
        }  
    }  
      
    class LabelToolbarItem: NSToolbarItem {  
         
        override init(itemIdentifier: NSToolbarItem.Identifier) {  
            super.init(itemIdentifier: itemIdentifier)  
              
            self.view = ToolbarLabelView()  
            self.view?.translatesAutoresizingMaskIntoConstraints = false  
        }  
    }
    

    If then I hide standard window title like this window?.titleVisibility = .hidden, only the custom toolbar item is there and it looks like window title. It looks as it should, even though it is not very clean solution.