首页 > 解决方案 > 自定义 NavigationbarButtonItem 显示在错误的位置

问题描述

我有一个名为banditButton 的UIbutton。我希望将此按钮设置为导航栏右侧的导航栏按钮项目。

我尝试将按钮设置如下。但是按钮被放置在屏幕的左上角。我正在使用 banditButton.frame 来调整按钮的大小。我给出的 X 和 Y 坐标为 0,但我没有覆盖要放置为 rightBarButtonItem 的按钮的位置吗?

    override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    banditButton.frame = CGRect(x: 0,
                                y: 0,
                                width: size, height: size)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: banditButton)
}

另一个问题是:我创建了一个名为“ profileButtonAndUsernameLabel ”的容器视图,它是 UIView()。这个 UIView 有 2 个子视图,分别称为“ profileButton ”和“ usernameLabel ”。此 UIView 应作为leftBarButtonItem执行。但是当下面的代码启动时,我的 UIView 不会显示在屏幕上的任何位置。基本上我希望这个 UIView 像Instagram Posts 中的 ProfilePicture 和 Username。头像在左边,用户名在右边。但这应该作为一个navigationLeftBarButtonItem。不知道我错过了什么。

提前致谢!

  profileButton.layer.cornerRadius = 25
    profileButton.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
    
    usernameLabel.frame = CGRect(x: profileButtonAndUsernameLabel.left + 55, y: profileButtonAndUsernameLabel.center.y, width: profileButtonAndUsernameLabel.width, height: profileButtonAndUsernameLabel.height)
    
    profileButtonAndUsernameLabel.addSubview(profileButton)
    profileButtonAndUsernameLabel.addSubview(usernameLabel)
    
    usernameLabel.text = "Username"
    
    
    if isPostInMusicGenre == false {
        //ProfileButton

        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: profileButtonAndUsernameLabel)
        
    }

标签: swiftuinavigationcontrolleruinavigationbaruinavigationitem

解决方案


推荐阅读