简体   繁体   English

IBInspectable / IBDesignable的Swift多继承解决方案?

[英]Swift multiple inheritance solution for IBInspectable/IBDesignable?

I've been playing with the IBInspectable/IBDesignable like in this article: http://nshipster.com/ibinspectable-ibdesignable/ . 我一直在像本文中一样使用IBInspectable / IBDesignable: http ://nshipster.com/ibinspectable-ibdesignable/。

It shows how you can make an extension to add extra editing options in storyboard. 它显示了如何进行扩展以在情节提要中添加额外的编辑选项。 The problem however is that you can't see these changes reflected in the preview. 但是,问题在于您无法在预览中看到这些更改。 For this you need to subclass, use IBDesignable and do the didset{} stuff. 为此,您需要子类化,使用IBDesignable并执行didset{}东西。

The problem with this is that you need to make a subclass of every stock UIView subclass. 问题是您需要为每个股票UIView子类创建一个子类。 So a subclass of UILabel , UITextField and so on. 因此是UILabelUITextField等的子类。 Every time you have to copy/paste the regular UIView stuff like borders and corner radius. 每次您必须复制/粘贴常规UIView内容(例如边框和角半径)时。

I don't believe Swift supports multiple inheritance, which would have made this much easier. 我不相信Swift支持多重继承,这会使事情变得容易得多。

Let's say your IBDesignable subclass of UIView is called IBView . 假设您的UIViewIBDesignable子类称为IBView Is there a way to make eg UILabel be a subclass of IBView instead of UIView ? 有没有办法使UILabel成为IBView的子类而不是UIView

In the end I'm looking if there is a way to make IBDesignable less tedious. 最后,我在寻找是否有一种方法可以使IBDesignable那么乏味。

Like you, I'm trying to find a better solution to work with IBDesignable. 像您一样,我正在尝试找到更好的解决方案来与IBDesignable一起使用。

What I did to avoid repeat the same code: 为了避免重复相同的代码,我做了以下操作:

  1. I made an extension of UIView to insert all the @IBInspectables I want (like corder radius, border width...). 我对UIView进行了扩展,以插入我想要的所有@IBInspectables(如Corder半径,边框宽度...)。
  2. I created my @IBDesignables that only inherit from UIView, UIButton (or any subclass of UIView I want) in order to render on Interface Builder. 我创建了@IBDesignables,它们仅继承自UIView,UIButton(或我想要的UIView的任何子类),以便在Interface Builder上呈现。

Check this code: 检查此代码:

extension UIView {

    @IBInspectable var cornerRadius: CGFloat {
        get {
            return layer.cornerRadius
        }
        set {
            layer.cornerRadius = newValue
            layer.masksToBounds = newValue > 0
        }
    }

    @IBInspectable var borderColor: UIColor? {
        get {
            return UIColor(cgColor: layer.borderColor ?? UIColor.clear.cgColor)
        }

        set {
            layer.borderColor = newValue?.cgColor
        }
    }

    @IBInspectable var borderWidth: Double {
        get {
            return Double(layer.borderWidth)
        }

        set {
            layer.borderWidth = CGFloat(newValue)
        }
    }
}

@IBDesignable
class BorderView: UIView { }

@IBDesignable
class BorderButton: UIButton { }

I hope it helps you! 希望对您有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM