ios - Swift - 在 UIView 的两个子类中重写一个方法

标签 ios swift uiview refactoring

我正在使用 UITextFieldUIButton 的自定义子类 - MyTextFieldMyButton

在这两种情况下,我都以这种方式创建圆边:

var round = true
override func layoutSublayers(of layer: CALayer) {
    super.layoutSublayers(of: layer)
    layer.cornerRadius = round ? self.frame.height/5.0 : 0
}

我试图找到一些通用的方法来使两个类都具有 round 字段并覆盖 layoutSublayers(...)。有什么方法比在每个类中粘贴相同的代码更好?

最佳答案

或者,如果您想要一种真正灵活的方式,您可以使用 View 样式概念。下面是您可以开始的简单实现:

typealias Style<T> = (T) -> Void

extension UIView {

    convenience init<V: UIView>(with styles: [Style<V>]) {
        self.init(frame: .zero)
        guard let view = self as? V else {
            assertionFailure("Could not apply style for \(V.self) to \(type(of: self))")
            return
        }
        styles.forEach { $0(view) }
    }
}

然后声明一些样式表

enum ViewStyle {

    static func rounded(radius: CGFloat) -> Style<UIView> {
        return { view in
            view.layer.cornerRadius = radius
            view.clipsToBounds = true
        }
    }

    static let lightGray: Style<UIView> = { view in
        view.backgroundColor = .lightGray
    }
}

像这样使用它

let button = UIButton(with: [ViewStyle.rounded(radius: 5.0)])
let textField = UITextField(with: [
    ViewStyle.rounded(radius: 8.0),
    ViewStyle.lightGray
])

它允许您重用预定义样式并混合它们以实现更复杂的设置,而无需创建自己的自定义子类。当然,这只是可以做的事情的一小部分,我鼓励你更深入:)

关于ios - Swift - 在 UIView 的两个子类中重写一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54679893/

相关文章:

iphone - UIView 性能 : opaque, backgroundColor,clearsContextBeforeDrawing?

ios - 如何检测 View 中的某些部分

ios - 无法使用 iphonesimulator9.2 为模拟器构建

iphone - iOS MVC 应用程序的关注点分离

ios - "pattern-match"运算符 ~= 在 Swift 中导致 "Binary operator ' ~= ' cannot be operand"错误

uiview - @IBInspectable 不更新 Storyboard

ios - Objective-C 中的警告 "Method definition not found"。从类别文件调用方法

iOS UIScrollView 问题

ios - 有什么方法可以为重复的 UI 元素(例如 UITableViewCells)设置手势识别器吗?

ios - 如何在iOS中获取两个已知子字符串之间的子字符串?