【问题标题】:Toggle between types depending on an enum case根据枚举案例在类型之间切换
【发布时间】:2021-02-01 12:52:43
【问题描述】:

我有一组颜色样式,我想将其应用于文本视图的内容,具体取决于它的样式是 ColorStyle.dark 还是 ColorStyle.light。

到目前为止,我正在通过将 textView 设置为从视图中调用 BlackTextView() 或 WhiteTextView() 来更改颜色。如何根据 ColorStyle 枚举动态设置标题和颜色样式?

比如说……

我有一个枚举来设置颜色样式,可以是深色、浅色或无色

public enum ColorStyle {
    case dark
    case light
    case none
}

我可以从 tableViewCell 将标题和 ColorStyle 传递给自定义视图

class TableViewCell: UITableViewCell {

    @IBOutlet weak var myView: MyView!
    
    func setup(viewModel: MyViewModel) {
        myView.titleLabel.text = viewModel.titleText
        myView.colorSytle = ColorSytle.dark
    }
}

该视图(符合 TextLayout)并且可以将 textView 设置为具有 BlackTextView 或 WhiteTextView 样式

public protocol TextLayout {
    associatedtype TextView: UITextView
    var textView: TextView { get }
}

@IBDesignable
public class MyView: View, TextLayout {
    
    public var colorStyle: ColorStyle = .none
    public var textView = BlackTextView()
    // public var textView = WhiteTextView()
}

总而言之,如何根据给定的枚举大小写在黑色或白色文本视图颜色方案之间切换,同时设置文本?

【问题讨论】:

    标签: swift generics enums uiview


    【解决方案1】:

    这样的事情怎么样?

    public class MyView: UIView {
        public var colorStyle: ColorStyle = .none {
          didSet {
            if colorStyle == .light {
              let newView = WhiteTextView()
              newView.text = textView.text
              textView.removeFromSuperview()
              addSubview(newView)
            } else {
              // do same thing for the dark view...
            }
          }
        }
        public var text: String {
          get {
            textView.text
          }
          set {
            textView.text = value
          }
        }
        private var textView: UIView = BlackTextView()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-28
      • 1970-01-01
      • 2015-11-16
      • 1970-01-01
      • 1970-01-01
      • 2016-02-27
      • 1970-01-01
      相关资源
      最近更新 更多