如何将SwiftUI按钮放入NSToolbar? [英] How to put SwiftUI button into NSToolbar?

查看:189
本文介绍了如何将SwiftUI按钮放入NSToolbar?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是使用附件视图控制器将SwiftUI插入NSToolbar的方式:

This is how SwiftUI can be inserted into NSToolbar using an accessory view controller:

import SwiftUI
import PlaygroundSupport

var hostingView = NSHostingView(rootView:
  ZStack {
    Color.clear
    HStack {
      Text("Hey")
      Text("SwiftUI")
    }
  }
  .padding()
  .edgesIgnoringSafeArea(.all)
)
hostingView.frame.size = hostingView.fittingSize

let titlebarAccessory = NSTitlebarAccessoryViewController()
titlebarAccessory.view = hostingView
titlebarAccessory.layoutAttribute = .trailing

let mask: NSWindow.StyleMask = [.titled, .closable, .miniaturizable, .resizable]
let window = NSWindow(
  contentRect: .init(x: 0, y: 0, width: 480, height: 300),
  styleMask: mask, backing: .buffered, defer: false)
window.center()
window.contentView = NSHostingView(rootView: Color(.windowBackgroundColor))
window.toolbar = .init()
window.titleVisibility = .hidden
window.addTitlebarAccessoryViewController(titlebarAccessory)

PlaygroundPage.current.liveView = window.contentView?.superview

上面的代码确实有效:

但是,如果我们插入按钮:

If we insert a button however:

HStack {
  Text("Hey")
  Button(action: {}) {
    Text("SwiftUI")
  }
}

它不能按预期工作:

有什么建议吗?

P. S.这是一个可行的解决方案:

HStack {
  Text("Hey")
    .offset(x: 0, y: -1)
  Button(action: {}) {
    Text("SwiftUI")
      .offset(x: 0, y: -7)
  }
}
.font(.caption)

推荐答案

将我的评论发布为每个请求的答案.不一定是可靠的解决方案,但可以使用一种变通办法

Posting my comment as an answer per request. Not necessarily a reliable solution but as a workaround you can use

Text("SwiftUI")
  .padding(EdgeInsets(top: -7, leading: 0, bottom: 0, trailing: 0))

按钮中文本"上的

.offset.无法保证解决方案能持续多久.

or .offset on the Text in the button. No guarantees on how long that will last as a solution.

这篇关于如何将SwiftUI按钮放入NSToolbar?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆