我一直在爲這一整天奮鬥 - 我需要在我的導航欄中添加一個視圖作爲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]
任何人有什麼我做錯了的想法? :-)
這裏是個愚蠢的問題。您是否關閉了'codedLabel'的自動識別掩碼?它不在你的代碼中。 – dfd
是的,使用程序化自動佈局的* all *視圖必須將'translatesAutoresizingMaskIntoConstraints'設置爲'false' – BallpointBen
@ BallpointBen-這可能是問題:)現在我至少可以移動箭頭!謝啦!我會發布最終的解決方案,當我得到它正常工作:)) –