我希望View Controller中的步进器每次单击时都会更新自定义UIView
中的颜色。我不确定问题是由于类的实例还是变量(redd1
,greenn1
和bluee1
)的值未被更改。
这是我的第一个档案:
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);
}
}
答案 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);
}
}