Is there a way to impersonate a View?

时间:2018-05-14 17:37:46

标签: swift uiview

I have just a quick question:

Is there a way to impersonate a View? I have designed a View in Storyboard. But now I want to use many Views which are exactly the same as the one designed in Storyboard. I basically just want to "copy" the view 7 times. I`ve tried

let testarray:[UIView] = [someview, someview, someview]

But then of course if I change the values of one view it changes the value of all views and thats not what I wont. I hope you understand what I want to do because my english skills are not that brilliant.

1 个答案:

答案 0 :(得分:0)

是的,可以使用Xibs。我个人这样做的方式是以下

  1. 我创建了一个(defvar ar-move-line-this-column nil) (defun ar-move-line-keep-column-intern (arg) (unless (eq last-command this-command) (setq ar-move-line-this-column (current-column))) (forward-line arg) (while (and (not (eolp)) (< (current-column) ar-move-line-this-column)) (forward-char 1))) (defun ar-forward-line-keep-column (&optional arg) "Go to current column of next line. If line is shorter, go to end of line" (interactive "p") (ar-move-line-keep-column-intern (or arg 1))) (defun ar-backward-line-keep-column (&optional arg) "Go to current column of line above. If line is shorter, go to end of line" (interactive "p") (ar-move-line-keep-column-intern (- arg))) 文件,里面有一个视图,让我们说.xib
  2. 在您的班级MyView.xib内创建一个.swift文件。在此内部放置所有MyView.swift和所有内容。
  3. @IBOutlet内,添加MyView.xib作为xib的所有者,并将出口链接到子视图
  4. 确保您的课程MyView扩展了您可以添加到项目中的以下课程MyView(这是我在项目中使用的课程)

    CustomXibView
    1. 如果您要创建视图,只需使用@IBDesignable class CustomXibView: UIView { @objc internal var defaultXib: String { return String(describing: type(of: self)) } override init(frame: CGRect) { super.init(frame: frame) loadXib(xib: defaultXib) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) loadXib(xib: defaultXib) } private func loadXib(xib: String) { // Load view let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: xib, bundle: bundle) let contentView = nib.instantiate(withOwner: self, options: nil)[0] as! UIView // use bounds not frame or it'll be offset contentView.frame = bounds // Make the view stretch with containing view contentView.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight] // Make sure layout uses superview margins preservesSuperviewLayoutMargins = true // Adding custom subview on top of our view addSubview(contentView) } }
    2. 进行初始化