gpt4 book ai didi

swift - 如何在运行时修改view.alphaValue并生效

转载 作者:行者123 更新时间:2023-11-30 10:39:25 25 4
gpt4 key购买 nike

我在运行时修改了 alphaValue 但没有任何效果,请问是什么问题。如何在运行时修改 alphaValue ?

我想在运行时调整 View 的alphaValue

Xcode 10.2.1 Swift 4.2

//
// ViewController.swift
// macosappalphaValuetest
//
// Created by miller on 2019/7/25.
// Copyright © 2019 miller. All rights reserved.
//

import Cocoa

class ViewController: NSViewController {

@IBAction func btnclick1(_ sender: Any) {
self.view.alphaValue = 0.8

}


override func viewDidLoad() {
super.viewDidLoad()

// Do any additional setup after loading the view.
}

override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}

override func viewWillAppear() {
super.viewWillAppear()
view.window?.isOpaque = false
view.window?.backgroundColor = NSColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 0.5)
self.view.alphaValue = 0.4
}

}

最佳答案

NSViewControllerviewWillAppear方法中,你的 View 窗口可能是nil。您可以通过打印print(view.window)来检查它。因此,您需要获取窗口的正确实例。参见下面的方法:

func validWindow() -> NSWindow? {
var window = NSApplication.shared.mainWindow
if (window == nil) {
window = NSApplication.shared.windows.first
}
return window
}

只需编写以下代码即可使窗口透明:

guard let window = self.validWindow() else { return }
window.alphaValue = 0.5

这对我来说效果很好。

输出:

enter image description here

递归地增加和减少 alpha 值:

func decreaseAlpha(_ window: NSWindow) {
let alpha = window.alphaValue - 0.1
if alpha < 0.0 {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
self.increaseAlpha(window)
}
return
}

window.alphaValue = alpha
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
self.decreaseAlpha(window)
}
}

func increaseAlpha(_ window: NSWindow) {
let alpha = window.alphaValue + 0.1
if alpha > 1.0 {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
self.decreaseAlpha(window)
}
return
}

window.alphaValue = alpha
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
self.increaseAlpha(window)
}
}

并在viewDidLoad:方法中写入:

guard let window = self.validWindow() else { return }
decreaseAlpha(window)

输出:

enter image description here

关于swift - 如何在运行时修改view.alphaValue并生效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57195319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com