CustomButton

适用于 macOS 应用的可自定义按钮

这是一个基于图层的 NSButton 子类,可以在正常状态和激活(按下)状态之间动画显示样式和颜色。

此软件包已在生产环境中使用,例如 Gifski

要求

安装

在 Xcode 的 “Swift Package Manager” 标签中添加 https://github.com/sindresorhus/CustomButton

用法

查看源代码,了解您可以更改哪些属性,并在示例应用中进行尝试。 默认情况下,它没有样式。

import Cocoa
import CustomButton

@main
final class AppDelegate: NSObject, NSApplicationDelegate {
	@IBOutlet weak var window: NSWindow!

	func applicationDidFinishLaunching(_ notification: Notification) {
		let button = CustomButton()
		button.translatesAutoresizingMaskIntoConstraints = false
		button.title = "CustomButton"
		button.activeBackgroundColor = .systemPink
		button.borderWidth = 1
		button.borderColor = .systemPink
		button.cornerRadius = 5
		button.textColor = .systemPink
		button.activeTextColor = .white

		let contentView = window.contentView!
		contentView.addSubview(button)

		NSLayoutConstraint.activate([
			button.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
			button.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
			button.widthAnchor.constraint(equalToConstant: 100),
			button.heightAnchor.constraint(equalToConstant: 30)
		])
	}
}

该按钮也可以在 Interface Builder 中编辑,但 Xcode 在 @IBDesignable 方面有很多 bug,所以我建议目前仅以编程方式使用它。

常见问题解答

你能支持 Carthage 和 CocoaPods 吗?

不可以,但是即使你主要使用 Carthage 或 CocoaPods,你仍然可以为此软件包使用 Swift Package Manager。

SwiftUI 不会让这个变得没有意义吗?

SwiftUI 确实使创建自定义外观的按钮变得容易得多,但是 SwiftUI 仍然不成熟,大多数公司在很长一段时间内都无法要求 macOS 10.15。 因此,这个软件包在未来几年内仍然有用。

相关

你可能也会喜欢我的应用