xcode 使用 Swift 扩展 UIView 类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26244889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 05:48:16  来源:igfitidea点击:

Extended UIView class using Swift

xcodemacosuiviewswiftuikit

提问by Aggressor

I have been trying to subclass a UIView and using the help of https://stackoverflow.com/a/24036440/3324388to handle the 'init(coder)' issue

我一直在尝试对 UIView 进行子类化并使用https://stackoverflow.com/a/24036440/3324388的帮助来处理 'init(coder)' 问题

However I keep running into snags with even the most basic attempts I'm hoping someone could post a simple example of the actual code needed to subclass a UIView with Swift.

但是,即使是最基本的尝试,我也一直遇到障碍,我希望有人可以发布一个简单的示例,说明使用 Swift 对 UIView 进行子类化所需的实际代码。

My current code is

我目前的代码是

//image class
import UIKit

class childView: UIView {


    var image:UIImage!

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

}

I do not want to pass this NSCoder object (I'm not sure what it does and it makes my code messy). Could you post an example of how to cleanly subclass a UIView and then how you would initialize it in another class?

我不想传递这个 NSCoder 对象(我不确定它是做什么的,它使我的代码变得混乱)。你能发布一个如何干净地子类化 UIView 的例子,然后你将如何在另一个类中初始化它?

I'd really love to extend my UIView classes to have some cool effects like drop shadows, auto scaling, and lots of other goods without having to create subviews to handle all that (like UIImageViews inside UIScrollViews)

我真的很想扩展我的 UIView 类以获得一些很酷的效果,如阴影、自动缩放和许多其他产品,而无需创建子视图来处理所有这些(如 UIScrollViews 中的 UIImageViews)

回答by Mundi

Seems really simple. Just following the code completion.

看起来真的很简单。只需按照代码完成即可。

class MyView : UIView {

    var image = UIImage()

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

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

var v = MyView()

I am initializing a dummy UIImageso you won't have an ugly surprise if you use your unwrapped version if it is nil.

我正在初始化一个虚拟对象,UIImage因此如果您使用未包装的版本,您将不会有一个丑陋的惊喜,如果它是nil.