gpt4 book ai didi

ios - Swift:自定义 UIView 未根据约束调整大小

转载 作者:行者123 更新时间:2023-11-28 06:57:13 27 4
gpt4 key购买 nike

我创建了一个从 XIB 文件加载的自定义 UIView。然后我将 View 添加到堆栈 View ,并在项目上设置宽度约束。

如果我从 Storyboard 中执行此操作,它会完美地工作,但是如果我从 Swift 中执行此操作,我将无法使 View 拉伸(stretch)到约束。 stackview 正在为 View 分配空间,但 View 不会拉伸(stretch)到该空间。

自定义 View swift代码:

import Foundation
import UIKit

@IBDesignable class TabButton: UIView {

@IBOutlet weak var label: UILabel!

@IBInspectable var TabText: String? {
get {
return label.text
}
set(TabText) {
label.text = TabText
label.sizeToFit()
}
}

override func intrinsicContentSize() -> CGSize {
return CGSize(width: UIViewNoIntrinsicMetric, height: UIViewNoIntrinsicMetric)
}

override init(frame: CGRect) {
// 1. setup any properties here

// 2. call super.init(frame:)
super.init(frame: frame)

// 3. Setup view from .xib file
xibSetup()
}

required init(coder aDecoder: NSCoder) {
// 1. setup any properties here

// 2. call super.init(coder:)
super.init(coder: aDecoder)!

// 3. Setup view from .xib file
xibSetup()
}

// Our custom view from the XIB file
var view: UIView!

func xibSetup() {
view = loadViewFromNib()

// use bounds not frame or it'll be offset
view.frame = bounds

// Make the view stretch with containing view
view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]

// Adding custom subview on top of our view (over any custom drawing > see note below)
addSubview(view)
}

func loadViewFromNib() -> UIView {

let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: "TabButton", bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView

self.roundCorners([.TopLeft, .TopRight], radius: 10)

return view
}
}

这是将 View (tabButton) 添加到堆栈 View (tabBar) 的 View Controller :

@IBOutlet weak var tabBar: UIStackView!

override func viewDidLoad() {
super.viewDidLoad()

let tabButton = TabButton(frame: CGRectZero)
tabButton.label.text = "All Videos"

tabButton.backgroundColor = UIColor.blackColor()

let widthConstraint = NSLayoutConstraint(item: tabButton, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 100)
tabButton.addConstraint(widthConstraint)

tabBar.insertArrangedSubview(tabButton, atIndex: 0)
}

我希望 tabButton“忽略”它的框架并根据堆栈 View 的高度和我设置的宽度约束调整大小。

我错过了什么?

更新:

我对自定义 View 的限制(基本上只是一个带标签的 View - 但我也计划将其用于更复杂的布局):

My constraints

最佳答案

试试这个:

let widthConstraint = NSLayoutConstraint (item: your_item_here, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: your_value_here)
self.view.addConstraint(widthConstraint)

关于ios - Swift:自定义 UIView 未根据约束调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33143361/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com