UIView如何实际推断出forFirstBaselineLayout属性?

问题描述

我目前正在读一本书,内容是Matt Neuburg编程iOS 13,深入研究视图,视图控制器和框架,偶然发现将view1(UIView)与另一个view2(UIView)对齐。 马特·诺伊伯格(Matt Neuburg)告诉:

”您可能希望能够将自定义UIView与其他视图对齐 根据他们的基准。这里的假设是您的视图有一个 子视图包含本身具有基线的文本。您的自定义视图 将在其实现中返回该子视图 forFirstBaselineLayout或forLastBaselineLayout。”

我试图检查这种方法是否真的有效。

override func viewDidLoad() {
    super.viewDidLoad()
    let view1 = UIView()
    view1.translatesAutoresizingMaskIntoConstraints = false
    view1.backgroundColor = UIColor.blue
    view.addSubview(view1)
           
    let view2 = UIView()
    view2.backgroundColor = UIColor.gray
    view2.translatesAutoresizingMaskIntoConstraints = false
    var textView2 = UITextView()
    textView2.frame = CGRect(x: 20,y: 50,width: 100,height: 120)
    textView2.text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s."
    view.addSubview(view2)
    view2.addSubview(textView2)
          
    view1.leadingAnchor.constraint(equalTo: self.view.layoutMarginsGuide.leadingAnchor).isActive = true
    view1.widthAnchor.constraint(equalToConstant: 150).isActive = true
    view2.widthAnchor.constraint(equalToConstant: 150).isActive = true
    view1.heightAnchor.constraint(equalToConstant: 250).isActive = true
    view2.heightAnchor.constraint(equalToConstant: 250).isActive = true
    view1.trailingAnchor.constraint(equalTo: view2.leadingAnchor,constant: -30).isActive = true
           
           
    view1.firstBaselineAnchor.constraint(equalTo: view2.firstBaselineAnchor).isActive = true
           

enter image description here

他再次写道:

“您的视图具有一个子视图,该子视图包含本身具有基线的文本。” 我用其子视图textView2创建view2,该子视图又具有 具体的基线。

接下来,他告诉:

”您的自定义视图将在其实现中返回该子视图 forFirstBaselineLayout或forLastBaselineLayout。”

当我在示例中使用firstBaselineAnchor约束视图时,Apple说:

”“当您对视图的 NSLayoutConstraint.Attribute.firstBaseline属性,“自动布局”使用 此(firstBaselineAnchor)方法返回的视图的基线。如果那个观点确实 没有基线,自动版式会使用视图的顶部边缘。“

因此,我的示例似乎使用了firstBaselineAnchor。如果作者说实话,则view2.forFirstBaselineLayout必须等于textView2。并且视图的位置必须与问题所附的屏幕快照中描述的实际结果不同。但是view2.forFirstBaselineLayout等于view2而不是其textView2子视图。

我是否正确理解了作者的话,或者我错过了一些事情,但是由于某种原因,他的话与现实不符。也许有人知道在什么情况下作者的陈述是正确的?或者,如果我对某事的解释不正确并且没有做出榜样,请帮助我。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)