gpt4 book ai didi

ios - 如何快速更改 Controller View 某些部分的颜色?

转载 作者:搜寻专家 更新时间:2023-11-01 07:07:51 25 4
gpt4 key购买 nike

我创建了一个自定义 UIView。我正在使用下面的代码将它的一部分颜色设置为其他颜色。

import Foundation

class BottomView:UIView {

override func draw(_ rect: CGRect) {
self.fillColor(with: .gray, width: 20)
}

func fillColor(with color:UIColor,width:CGFloat) {

let topRect = CGRect(x:0, y:0, width : width, height: self.bounds.height);
color.setFill()
UIRectFill(topRect)

}

}

现在我的 View 有一些颜色的初始部分,因为灰色和其余颜色不同。现在从 Controller ,如果我尝试将它的颜色更改为绿色,它不会从开始位置更改。它的颜色在初始颜色后发生了变化。

请告诉我如何将背景颜色完全设置为绿色。

最佳答案

您可以在底部 View 上使用setNeedsDisplay 并在设置backgroundColor 时重绘它。

setNeedsDisplay()

Marks the receiver’s entire bounds rectangle as needing to be redrawn.

You can use this method or the setNeedsDisplay(_:) to notify the system that your view’s contents need to be redrawn. This method makes a note of the request and returns immediately. The view is not actually redrawn until the next drawing cycle, at which point all invalidated views are updated.

示例:

<强>1。 BottomView

class BottomView:UIView
{
var showGray = true

override func draw(_ rect: CGRect)
{
if showGray
{
self.fillColor(with: .gray, width: 20)
}
}

func fillColor(with color:UIColor,width:CGFloat)
{
let topRect = CGRect(x:0, y:0, width : width, height: self.bounds.height);
color.setFill()
UIRectFill(topRect)
}
}

<强>2。在你的 UIViewController

self.bottomView.showGray = false
self.bottomView.setNeedsDisplay()
self.bottomView.backgroundColor = .green

关于ios - 如何快速更改 Controller View 某些部分的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47013997/

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