自定义元素的子图层未在模拟器中呈现,在界面构建器

时间:2017-03-21 00:07:39

标签: ios swift interface-builder

我正在尝试创建一个自定义渐变图层,我可以在Interface Builder中重用我的不同视图。我创建了以下类:

导入UIKit

@IBDesignable
class MyGradientLayer: UIView {

    let gradient = CAGradientLayer()

    public override init(frame: CGRect) {
        super.init(frame: frame)

        gradient.colors = [startColor.cgColor, endColor.cgColor]
        gradient.frame = self.bounds
        gradient.locations = [0, 1]
        self.layer.insertSublayer(gradient, at: 0)
    }

    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    @IBInspectable
    public var startColor: UIColor = UIColor.init(red: 1, green: 0.364, blue: 0.22352, alpha: 1.0) {
        didSet {
            gradient.colors = [startColor.cgColor, endColor.cgColor]
        }
    }

    @IBInspectable
    public var endColor: UIColor = UIColor.init(red: 1, green: 0.1607, blue: 0.40392, alpha: 1.0) {
        didSet {
            gradient.colors = [startColor.cgColor, endColor.cgColor]
        }
    }

    override func layoutSubviews() {
        gradient.frame = self.bounds
        gradient.locations = [0, 1]
        super.layoutSubviews()
    }

}

然后我在我的ViewController中添加了一个UIView,并在Identity检查器中将该类设置为MyGradientLayer。我漂亮的小渐变视图然后在Interface Builder中渲染得很好。我继续设置约束以占据整个屏幕(我尝试了手动和自动约束)。一切都很好,对吧?

不,它不会在模拟器中渲染渐变图层。但是,我知道视图就在那里并被放到屏幕上,因为我可以在IB中设置UIView的背景颜色,并在整个屏幕上显示。

为什么我的自定义UIView中的渐变图层未在模拟器中渲染?

谢谢!

1 个答案:

答案 0 :(得分:0)

看看如果你改变了" init"会发生什么?如下:

extern crate typenum;
use typenum::Unsigned;
use std::marker::PhantomData;

struct Dynamic {}

// N needs to be some kind of union type of Unsigned and Dynamic, but don't know how
struct Vector<E, N: Unsigned> {
    vec: Vec<E>,
    _marker: PhantomData<(N)>,
}

impl<E, N: Unsigned> Vector<E, N> {
    fn new(vec: Vec<E>) -> Self {
        assert!(N::to_usize() == vec.len());
        Vector {
            vec: vec,
            _marker: PhantomData,
        }
    }
}

fn add<E, N: Unsigned>(vector1: &Vector<E, N>, vector2: &Vector<E, N>) {
    print!("Implement addition here")
}

fn main() {
    use typenum::{U3, U4};
    let vector3 = Vector::<usize, U3>::new(vec![1, 2, 3]);
    let vector4 = Vector::<usize, U4>::new(vec![1, 2, 3, 4]);
    // Can I make the default be Dynamic here?
    let vector4_dynamic = Vector::new(vec![1, 2, 3, 4]);

    add(&vector3, &vector4); // should fail to compile
    add(&vector3, &vector4_dynamic); // should fail at runtime
}

根据其使用方式,您可能需要设置一个标志以防止多次调用commonInit。试一试看看。