【问题标题】:Custom subview not loading in xib自定义子视图未在 xib 中加载
【发布时间】:2017-02-05 23:56:55
【问题描述】:

我正在尝试在 textfield 中创建一个按钮,所以我创建了一个按钮并在 xibSetup() 中调用该函数。在运行程序时,该函数被调用。但没有加载到应用程序中。卡在里面了。

class NormalLogin: UIView {

weak var delegate:NormalLoginDelegate?
@IBOutlet weak var passwordField: UnderLinedTextField!
var view: UIView!
func showHideButton() {
    let btn = UIButton(frame: CGRect(x: self.frame.width - 70 , y: self.frame.size.height - 20 , width: 50, height: 20))
    btn.backgroundColor = UIColor.blackColor()
    btn.layer.borderWidth = 5
    btn.layer.borderColor = UIColor.blackColor().CGColor
    btn.setTitle("Click Me", forState: UIControlState.Normal)
    self.passwordField.addSubview(btn) // add to view as subview   
}

override init(frame: CGRect) {
    super.init(frame: frame)
    xibSetup()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    xibSetup()
}

func xibSetup() {
    view = loadViewFromNib()
    view.frame = bounds
    view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
    showHideButton() // Custom button i made
    addSubview(view)
}

func loadViewFromNib() -> UIView {
    let bundle = NSBundle(forClass: self.dynamicType)
    let nib = UINib(nibName: "NormalLogin", bundle: bundle)
    let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
    return view
}

}

我做错了吗?

【问题讨论】:

  • 你确定你给按钮框架的X和Y点是正确的吗?因为我猜应该是根据密码字段的框架而不是self.view。

标签: ios swift xib


【解决方案1】:

我猜这是因为你给按钮提供了错误的框架

试试这个

let btn = UIButton(frame: CGRect(x: self.passwordField.frame.width - 70 , y: self.passwordField.frame.height - 20 , width: 50, height: 20))

【讨论】:

  • 密码字段:UnderLinedTextField!没有成员宽度/高度。
  • 已更新。我只是指出按钮框架应该根据密码字段。
猜你喜欢
  • 2015-09-18
  • 2016-02-01
  • 2020-05-16
  • 1970-01-01
  • 1970-01-01
  • 2013-10-08
  • 2017-07-22
  • 1970-01-01
  • 2013-04-07
相关资源
最近更新 更多