ios - 无法更改 View 中绘制的圆的颜色

标签 ios swift uiview

我正在尝试更新我在 UIView 的子类中创建的圆圈的颜色通过在类中创建一个方法来更新颜色,如下所示,但颜色不会改变。

import UIKit

class badge: UIView {

    struct mine {
        static var p = UIBezierPath(ovalInRect: CGRectMake(0,0,100,100))

}

override func drawRect(rect: CGRect) {
    // Drawing code


    UIColor.blueColor().setFill()
    mine.p.fill()        

}


func colour(whatColour: String) {

    UIColor.redColor().setFill()
    mine.p.fill()
    self.setNeedsDisplay()

}
}

// The above is referenced in view controller with

@IBOutlet weak var myBadge: badge!

// change function colour is called with 

myBadge.colour()

// but the colour of the circle does not change (its still filled in blue)
}

我做错了什么?

最佳答案

更新:Swift 3(和 Swift 4)语法:

setNeedsDisplay 使 draw 再次运行,并将填充颜色设置回蓝色。尝试向您的 Badge View 添加一个属性来存储 desiredColour:

class Badge: UIView {

    var desiredColour: UIColor = .blue

    struct mine {
        static var p = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 100, height: 100))
    }

    override func draw(_ rect: CGRect) {
        // Drawing code

        desiredColour.setFill()
        mine.p.fill()
    }

    func colour() {
        desiredColour = .red
        self.setNeedsDisplay()
    }
}

如果您将didSet 添加到desiredColour,您可以让它为您调用setNeedsDisplay,然后您甚至不需要颜色功能。所以要使用它,您只需调用 myBadge.desiredColour = .red View 就会重绘!

class Badge: UIView {

    var desiredColour: UIColor = .blue {
        didSet {
            self.setNeedsDisplay()
        }
    }

    struct mine {
        static var p = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 100, height: 100))
    }

    override func draw(_ rect: CGRect) {
        // Drawing code

        desiredColour.setFill()
        mine.p.fill()
    }
}

它在 Swift Playground 中运行:

Badge example in a Playground

关于ios - 无法更改 View 中绘制的圆的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28174999/

相关文章:

iphone - 进行数据库备份

ios - 显示没有导航 View Controller 的后退按钮

iphone - 显示蜂窝数据已关闭警报

ios - 将 TableView 部分标题传递给另一个 View 的导航栏标题

ios - 单向一对多的核心数据关系

swift - Alamofire 库不响应 Swift 包管理器

uiview - 在 Storyboard中重用 uiview xib

ios - 使用 UIImageView 或 UIView 快速绘图

ios - UITableView 和 UICollectionView 的通用单元格

ios - RxSwift 崩溃 "Maybe delegate was already set in xib or storyboard and now it’ 被代码覆盖。”