【问题标题】:Initializing UIControl using programmatically VFL constraints (iOS Swift)使用编程 VFL 约束初始化 UIControl (iOS Swift)
【发布时间】:2018-05-29 00:57:56
【问题描述】:

我正在处理几个需要以编程方式创建的自定义 UIControl 对象。通常在使用 AutoLayout 时,我只传递一个 CGRect。使用视觉格式语言时:

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

UIControl 类中的 ViewDidLoad() 中的约束方法不会调用,并且 CAShapeLayers 不会更新。自定义按钮/滑块/旋钮等工作但不可见,我可以在触摸时立即更新形状。不是很有帮助。加载视图后,如何在屏幕上显示使用 VFL 的自定义 UIControl?这就是我想做的:

import UIKit

class ViewController: UIViewController {

   let knob = Knob()
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.addSubview(knob)
        knob.translatesAutoresizingMaskIntoConstraints = false
        let views = [
            "slider": knob
        ]

        let formatV = "V:|-[knob(300)]-|"
        let formatH = "H:|-[knob(300)]-|"

        let VC = NSLayoutConstraint.constraints(withVisualFormat: formatV, options: NSLayoutFormatOptions(), metrics: nil, views: views)
        let HC = NSLayoutConstraint.constraints(withVisualFormat: formatH, options: NSLayoutFormatOptions(), metrics: nil, views: views)

        self.view.addConstraints(VC)
        self.view.addConstraints(HC)
        knob.addTarget(self, action: #selector(knobRotated(_:)), for: .touchDown)
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @objc func knobRotated(_ sender: Knob) {
        print(sender.value)
    }
}

或者创建一个同时适用于 AutoLayout 和 VFL 的 UIControl 的最佳方法是什么?

【问题讨论】:

    标签: ios swift xcode9


    【解决方案1】:

    UIControlUIView 的子类,所以对它们进行类似的处理。了解UIView的生命周期,它有多种方法,是解决问题的关键。从它们内部打印并查看它们何时以及多久发射一次。以下是子类化UIView 时使用的更常见的生命周期方法。

    class CustomButton: UIControl {
        override init(frame: CGRect) {
            super.init(frame: frame)
            print("init")
        }
    
        override func updateConstraints() {
            print("update constraints")
            super.updateConstraints() // in this method, super is to be called last
        }
    
        override func layoutSubviews() {
            super.layoutSubviews()
            print("layout subviews")
        }
    }
    

    更多阅读:https://developer.apple.com/documentation/uikit/uiview

    【讨论】:

    • 非常感谢!这就是我需要的:覆盖 open func layoutSubviews() { super.layoutSubviews() updateLayer() }
    • 虽然 OP 表示感谢,但引起我注意的是您的答案中没有 VFL。要么这是对问题的糟糕回答,要么 - 更有可能 - 对糟糕问题的良好回答。
    猜你喜欢
    • 1970-01-01
    • 2017-04-26
    • 2020-05-30
    • 1970-01-01
    • 1970-01-01
    • 2016-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多