现在我已经为此奋斗了一整天--我需要在导航栏中添加一个视图作为rightBarButtonItems,其中包含一个UILabel和一个UIImageView。因此,我需要以编程方式创建该视图,以编程方式设置约束,并将该视图添加为rightBarButtonItems。
我想达到的目标是:
。
。
我得到的是:
似乎无论我做什么,我都无法移动向下箭头..它需要在标签的右侧,并与中心Y对齐。
这是我的代码:
//Elements
let containerView = UIView()
containerView.frame = CGRect(x: 0, y: 0, width: 90, height: 30)
containerView.backgroundColor = UIColor.blueColor()
let codedLabel:UILabel = UILabel()
codedLabel.frame = CGRect(x: 0, y: 0, width: 80, height: 30)
codedLabel.textAlignment = .Center
codedLabel.text = "FILTRER"
codedLabel.numberOfLines = 1
codedLabel.textColor = UIColor.redColor()
codedLabel.font = UIFont(name: Constants.ubuntuBold, size: 18.0)!
codedLabel.backgroundColor = UIColor.lightGrayColor()
codedLabel.sizeToFit()
let codedImageView: UIImageView = UIImageView()
codedImageView.frame = CGRect(x: 0, y: 0, width: 10, height: 5.7)
codedImageView.image = UIImage(named: "dragToRefreshArrow")
codedImageView.backgroundColor = UIColor.cyanColor()
containerView.addSubview(codedLabel)
containerView.addSubview(codedImageView)
containerView.sizeToFit()
//Constraints
containerView.translatesAutoresizingMaskIntoConstraints = false
//Label
NSLayoutConstraint(item: codedLabel, attribute: .Top, relatedBy: .Equal, toItem: containerView, attribute: .Top, multiplier: 1, constant: 0).active = true
NSLayoutConstraint(item: codedLabel, attribute: .Bottom, relatedBy: .Equal, toItem: containerView, attribute: .Bottom, multiplier: 1, constant: 0).active = true
NSLayoutConstraint(item: codedLabel, attribute: .Leading, relatedBy: .Equal, toItem: containerView, attribute: .Leading, multiplier: 1, constant: 0).active = true
NSLayoutConstraint(item: codedLabel, attribute: .Trailing, relatedBy: .Equal, toItem: containerView, attribute: .Trailing, multiplier: 1, constant: 0).active = true
//ImageView
NSLayoutConstraint(item: codedImageView, attribute: .Leading, relatedBy: .Equal, toItem: codedLabel, attribute: .Leading, multiplier: 1, constant: 0).active = true
NSLayoutConstraint(item: codedImageView, attribute: .Trailing, relatedBy: .Equal, toItem: containerView, attribute: .Trailing, multiplier: 1, constant: 0).active = true
NSLayoutConstraint(item: codedImageView, attribute: .CenterY, relatedBy: .Equal, toItem: codedLabel, attribute: .Top, multiplier: 1, constant: 0).active = true
let item = UIBarButtonItem()
item.customView = containerView
var negativeSpace:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil)
negativeSpace.width = -10.0
self.navigationItem.rightBarButtonItems = [negativeSpace, item]
有人知道我做错了什么吗?:-)
2条答案
按热度按时间3wabscal1#
为了使箭头(codedImageView)位于标签(codedLabel)的右侧,对齐CenterY并位于容器(ContainerView)内部,您需要以下约束:
这产生了以下约束:
看到第一个和第三个约束有什么不同吗?在示例中,您将它附加到codedLabel的左上角,而不是右中角。
rbpvctlc2#
您需要将约束添加到视图中。类似于: