以编程方式将UIView放在UILabel后面

问题描述 投票:2回答:2

我想问。我想在uilabel后面创建一个UIView,现在我从collectionview创建分段的Controll。如何在uilabel后面制作uiview?这是我的代码

nameLabel.translatesAutoresizingMaskIntoConstraints = false
        addSubview(nameLabel)
        NSLayoutConstraint.activate([
            nameLabel.topAnchor.constraint(equalTo: topAnchor),
            nameLabel.leadingAnchor.constraint(equalTo: leadingAnchor),
            nameLabel.bottomAnchor.constraint(equalTo: bottomAnchor),
            nameLabel.trailingAnchor.constraint(equalTo: trailingAnchor)
            ])

        let backgroundView = UIView()
        backgroundView.backgroundColor = .white
        backgroundView.translatesAutoresizingMaskIntoConstraints = false
        addSubview(backgroundView)
        insertSubview(backgroundView, aboveSubview: nameLabel)
        backgroundView.leadingAnchor.constraint(equalTo: nameLabel.leadingAnchor).isActive = true
        backgroundView.bottomAnchor.constraint(equalTo: nameLabel.bottomAnchor).isActive = true
        backgroundView.widthAnchor.constraint(equalTo: nameLabel.widthAnchor, multiplier: 1).isActive = true
        backgroundView.heightAnchor.constraint(equalToConstant: 48).isActive = true
swift autolayout
2个回答
3
投票

视图被添加回到最前面。 addSubview(backgroundView)之前的addSubview(newLabel)

类似这样的方法应该起作用:

let backgroundView = UIView()
backgroundView.backgroundColor = .white
backgroundView.translatesAutoresizingMaskIntoConstraints = false
addSubview(backgroundView)
nameLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(nameLabel)

NSLayoutConstraint.activate([
    nameLabel.topAnchor.constraint(equalTo: topAnchor),
    nameLabel.leadingAnchor.constraint(equalTo: leadingAnchor),
    nameLabel.bottomAnchor.constraint(equalTo: bottomAnchor),
    nameLabel.trailingAnchor.constraint(equalTo: trailingAnchor),
    backgroundView.leadingAnchor.constraint(equalTo: nameLabel.leadingAnchor),
    backgroundView.bottomAnchor.constraint(equalTo: nameLabel.bottomAnchor),
    backgroundView.widthAnchor.constraint(equalTo: nameLabel.widthAnchor, multiplier: 1),
    backgroundView.heightAnchor.constraint(equalToConstant: 48)
])

0
投票

您可以使用@Vacawama答案,或者您应该注意到Apple提供了2种API,例如:

func sendSubviewToBack(_ view: UIView)

func bringSubviewToFront(_ view: UIView)

因此您可以通过编程方式处理视图层次结构。

也许您可以尝试将backgroundView移到情节提要中标签的上方,因此可以将其放在情节提要中(因为它是情节提要中的先入先出)。

或使用sendSubviewToBack(backgroundView)

或使用bringSubviewToFront(nameLabel)

view.addSubview(backgroundView)然后是view.addSubview(nameLabel)

© www.soinside.com 2019 - 2024. All rights reserved.