在iOS应用程序的导航栏中对齐项目

时间:2020-06-11 22:26:51

标签: ios swift layout uinavigationbar frame

我有一个导航栏,其中包含一个带有名称和照片的自定义视图。此customview的布局包含使用锚对齐的子视图。然后,我尝试添加一个要显示在导航栏右侧的按钮,因此我像这样添加了它,之所以这样添加它而不是传统方式是因为,如果我将其用作传统意义上的背景图片:

        //Adding Unmatch Button
        let unmatchitem = UIBarButtonItem(image: UIImage(named: "heartbreak")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(unmatchTapped))
        navigationItem.rightBarButtonItem = unmatchitem

但是它像这样显示在我的应用程序中:

enter image description here

如您所见,右栏按钮位于中间。不应该的。我创建customview的方式是使用锚点,下面是我拥有的一些锚点:

图像锚点

        profileImageView.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true
        profileImageView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
        profileImageView.widthAnchor.constraint(equalToConstant: 40).isActive = true
        profileImageView.heightAnchor.constraint(equalToConstant: 40).isActive = true

名称标签和标题视图的锚点,其中包含一个包含标签和图像的容器视图

        nameLabel.leftAnchor.constraint(equalTo: profileImageView.rightAnchor, constant: 8).isActive = true
        nameLabel.centerYAnchor.constraint(equalTo: profileImageView.centerYAnchor).isActive = true
        nameLabel.rightAnchor.constraint(equalTo: containerView.rightAnchor).isActive = true
        nameLabel.heightAnchor.constraint(equalTo: profileImageView.heightAnchor).isActive = true

        containerView.centerXAnchor.constraint(equalTo: titleView.centerXAnchor).isActive = true
        containerView.centerYAnchor.constraint(equalTo: titleView.centerYAnchor).isActive = true

我不确定我可以做些什么来使此右侧按钮实际上位于右侧。因为在添加右按钮之前,我的customview已完美居中,所以我不认为需要更改其约束,而与我的自定义按钮有关,但是我找不到锚属性,因此我不确定如何将其向右对齐。任何帮助,将不胜感激。

编辑: 我相信解决方案是将按钮添加到我创建的自定义视图中。使用以下代码开始工作:

        //Adding Unmatch Button to titleview
        let unmatchButton = UIButton()
        unmatchButton.setBackgroundImage(UIImage(named: "heartbreak")?.withRenderingMode(.alwaysOriginal), for: .normal)
        titleView.addSubview(unmatchButton)
        unmatchButton.translatesAutoresizingMaskIntoConstraints = false
        //create size for the button
        unmatchButton.widthAnchor.constraint(equalToConstant: 40).isActive = true
        unmatchButton.heightAnchor.constraint(equalToConstant: 40).isActive = true
//        Unmatch Button Constraints
        unmatchButton.leftAnchor.constraint(equalTo: containerView.rightAnchor, constant: 32).isActive = true
//        unmatchButton.leftAnchor.constraint(equalTo: nameLabel.rightAnchor).isActive = true
        unmatchButton.centerYAnchor.constraint(equalTo: profileImageView.centerYAnchor).isActive = true

        self.navigationItem.titleView = titleView

我遇到的一个问题是,如何将其锚定在导航栏的右侧。因为如果我将其锚定在名称的左侧,则该容器将无法工作,因为该容器会根据名称长度进行拉伸,因此我希望通过将其锚定在我的导航栏的右侧,使其始终永久位于同一位置,但我不知道该如何锚定。我尝试过:

        unmatchButton.rightAnchor.constraint(equalTo: (navigationController?.navigationBar.rightAnchor)!).isActive = true

但是我得到一个错误,因为他们没有锚祖先,所以它不能这样做。

0 个答案:

没有答案