Swift UIView自定义视图在ViewController操作后不会更新

时间:2016-01-29 19:44:29

标签: ios swift uiview instance viewcontroller

我希望View Controller中的步进器每次单击时都会更新自定义UIView中的颜色。我不确定问题是由于类的实例还是变量(redd1greenn1bluee1)的值未被更改。

这是我的第一个档案:

class ViewController: UIViewController {
    var colors = UIView1();
    @IBOutlet var redStepper: UIStepper!
    @IBOutlet var greenStepper: UIStepper!
    @IBOutlet var blueStepper: UIStepper!

    @IBAction func redChange(sender: UIStepper)
    {
        redValue.text = Int(sender.value).description;
        colors.redd1 = Double(sender.value);
        //self.view.setNeedsDisplay()
    }
    @IBAction func greenChange(sender: UIStepper)
    {
        greenValue.text = Int(sender.value).description;
        colors.greenn1 = Double(sender.value);
        //self.view.setNeedsDisplay()
    }
    @IBAction func blueChange(sender: UIStepper)
    {
        blueValue.text = Int(sender.value).description;
        colors.bluee1 = Double(sender.value);
        //self.view.setNeedsDisplay()
    } 
}

这是我的第二个档案:

class UIView1: UIView {
    var redd1 = 0.0;
    var greenn1 = 0.0;
    var bluee1 = 0.0;

    override init(frame: CGRect)
    {
        super.init(frame: frame)
    }
    required init?(coder aDecoder: NSCoder)
    {
        super.init(coder: aDecoder)
    }
    override func drawRect(rect: CGRect)
    {
        let circle = UIView(frame: CGRect(x: -75.0, y: -40.0, width: 200.0, height: 200.0))
        circle.layer.cornerRadius = 50.0;
        let startingColor = UIColor(red: (CGFloat(redd1))/255, green: (CGFloat(greenn1))/255, blue: (CGFloat(bluee1))/255, alpha: 1.0)
        circle.backgroundColor = startingColor;
        addSubview(circle);
    }
}

1 个答案:

答案 0 :(得分:0)

drawRect仅在添加视图时调用,因此在您的示例中,drawRect被调用一次,而不是在更改步进器之后。

而是将步进器文件更改为:

@IBOutlet var redStepper: UIStepper!
@IBOutlet var greenStepper: UIStepper!
@IBOutlet var blueStepper: UIStepper!

@IBAction func redChange(sender: UIStepper) {
    redValue.text = Int(sender.value).description;
    colors.redd1 = Double(sender.value);
    updateColor()
}

@IBAction func greenChange(sender: UIStepper) {
    greenValue.text = Int(sender.value).description;
    colors.greenn1 = Double(sender.value);
    updateColor()
}

@IBAction func blueChange(sender: UIStepper) {
    blueValue.text = Int(sender.value).description;
    colors.bluee1 = Double(sender.value);
    updateColor()
} 

然后将updateColor函数添加到您的UIView1类:

class UIView1: UIView {

    var redd1 = 0.0;
    var greenn1 = 0.0;
    var bluee1 = 0.0;

    func updateColor() {
        let circle = UIView(frame: CGRect(x: -75.0, y: -40.0, width: 200.0, height: 200.0))
        circle.layer.cornerRadius = 50.0;
        let startingColor = UIColor(red: (CGFloat(redd1))/255, green: (CGFloat(greenn1))/255, blue: (CGFloat(bluee1))/255, alpha: 1.0)
        circle.backgroundColor = startingColor;
        addSubview(circle);
    }
}