如何快速从控制器更改视图某些部分的颜色? [英] How to change color of some part of view from controller in swift?

查看:17
本文介绍了如何快速从控制器更改视图某些部分的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个自定义的 UIView.我使用下面的代码将它作为其他颜色的一部分.

I have created a custom UIView.I am making it's some part of color as other color using below code.

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)

    }

}

现在我的视图有一些颜色的初始部分为灰色 &它的其余部分颜色不同.现在从控制器,如果我尝试将其颜色更改为绿色,则它不会从开始位置更改.初始颜色后颜色发生变化.

Now my view has some initial part of color as gray & rest of its color is different. Now from controller if i try to change it's color to green the it is not changed from start position. It's color changed after inital color.

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

Please let me know how i can completely set background color to green.

推荐答案

您可以在 bottom view 上使用 setNeedsDisplay 并在设置backgroundColor.

You can use setNeedsDisplay on your bottom view and redraw it when setting the backgroundColor.

setNeedsDisplay()

将接收者的整个边界矩形标记为需要重绘.

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

您可以使用此方法或 setNeedsDisplay(_:) 来通知系统,您的视图内容需要重新绘制.这种方法使请求的注释并立即返回.观点不是实际上重绘直到下一个绘制周期,此时所有更新无效的视图.

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

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

这篇关于如何快速从控制器更改视图某些部分的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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