2021年1月26日星期二

How to equally align items of different length in status item in menubar?

I have a loop with the contents akin to the following one. val1 and val2 are values of a column - first and second row(see the pic)

The problem is the dots move as the values get updated. How can I make them consistent like a colon in a watch?

 let paragraphStyle = NSMutableParagraphStyle()   ...   paragraphStyle.alignment = .right     var top: [String] = []   var bot: [String] = []      ...     for loop        var spacing = val1.count > val2.count ? val1.count : val2.count                                   while spacing >= val2.count {       val2 = "\u{00A0}" + val2       spacing -= 1     }                                                       while spacing >= val1.count {       val1 = "\u{00A0}" + val1       spacing -= 1     }     top.append(val1)   bot.append(val2)     end for loop    let row1 = NSAttributedString(string: "\n" + top.joined(separator: "\u{00A0}\u{2022}\u{00A0}"), attributes: textAttr)    let row2 = NSAttributedString(string: "\n" + bot.joined(separator: "\u{00A0}\u{2022}\u{00A0}"), attributes: textAttr)    ...    var rows = NSMutableAttributedString(attributedString: NSAttributedString(string: ""))  rows.append(row1)  rows.append(row2)  ...    statusItem?.button?.attributedTitle = rows  

enter image description here


UPDATE

I added the following code. There're no dot separators but the space in between the items is consistent now.

The problem is NSStatusItem.variableLength in statusItem = statusBar.statusItem(withLength: NSStatusItem.variableLength) doesn't seem to work anymore.

        let stack = NSStackView(views: [              StatusItemSectionView(),              StatusItemSectionView()          ])                     statusItem?.button?.addSubview(stack)          statusItem?.button?.addConstraint(NSLayoutConstraint(item: stack, attribute: .leading, relatedBy: .equal, toItem: statusItem?.button, attribute: .leading, multiplier: 1, constant: 30))  

enter image description here


UPDATE

It also seems that the approach with nested NSView has issues with the text color switching: In dark mode, clicking the status item keeps the text color white as expected.

But in regular/light mode the text color is black in both cases highlighted(clicked) and non-highlighted.

Detecting the current appearance and setting the color of each label of section doesn't seem right to me(I may be wrong)

enter image description here

https://stackoverflow.com/questions/65874087/how-to-equally-align-items-of-different-length-in-status-item-in-menubar January 25, 2021 at 01:57AM

没有评论:

发表评论