以编程方式添加UILabel不可见

时间:2018-07-24 08:53:58

标签: ios swift uilabel

我正在这里练习,我认为SearchBar并已使用

  func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) 

一旦用户开始书写,我就会隐藏自己的视图,并以编程方式创建另一个视图

这是我的概念,一旦我开始写作,我的第二个视图就会出现: Gif

但是一旦我正确添加了第二个视图,我想向其中添加一个UILabel。这是我的代码:

    self.word_of_the_day_view.isHidden = true // main view

    self.popularView.frame = CGRect(x: self.searcy_bar_view.frame.minX, y: self.searcy_bar_view.frame.maxY + 15, width: self.searcy_bar_view.frame.width, height: self.searcy_bar_view.frame.height) // don't mind the height and width


    self.popularView.backgroundColor = .white
    self.popularView.layer.cornerRadius = self.searcy_bar_view.layer.cornerRadius
    self.popularView.popIn() // just an animation
    is_popular_added = true

    self.view.addSubview(popularView)

    let label_1 = UILabel()
    label_1.frame = CGRect(x: self.popularView.frame.minX + 3, y: self.popularView.frame.minY, width: self.popularView.frame.width, height: 20)
    label_1.font = UIFont(name: "avenirnext-regular", size: 13)
    label_1.text = "Hello World!"
    label_1.layer.borderColor = UIColor.red.cgColor
    popularView.addSubview(label_1)

但是在运行时,甚至没有添加UILabel。

enter image description here

非常感谢您阅读问题!

3 个答案:

答案 0 :(得分:2)

您需要了解Frame和Bounds之间的区别。 视图的框架是视图在其超级视图中的位置,因此其原点可以具有CGPoint的任何值。 边界只是视图本身,因此其原点始终为(0,0)

我认为问题是

label_1.frame = CGRect(x: self.popularView.frame.minX + 3, y: self.popularView.frame.minY, width: self.popularView.frame.width, height: 20)

尝试更改

label_1.frame = CGRect(x: self.popularView.bounds.minX + 3, y: self.popularView.bounds.minY, width: self.popularView.frame.width, height: 20)

label_1.frame = CGRect(x: 3, y: 0, width: self.popularView.frame.width, height: 20)

答案 1 :(得分:1)

In your code

label_1.frame = CGRect(x: self.popularView.frame.minX + 3, y: self.popularView.frame.minY, width: self.popularView.frame.width, height: 20)

This is because self.popularView.frame.minX and self.popularView.frame.minY have some +value that crosses the boundary of the current view on which you are trying to add label_1. you should use self.popularView.bounds.origin.x and self.popularView.bounds.origin.y

Difference between bounds and frame

frame = a view's location and size with respect to the parent view's coordinate system

bounds = a view's size using its own coordinate system

答案 2 :(得分:0)

此问题是由于边框和界限之间的混乱所致。我的应用程序中也出现了类似的问题。

UIView边界是矩形,表示为相对于其自身坐标系(0,0)的位置(x,y)和大小(宽度,高度)

UIView框架是矩形,表示为相对于其所包含的超级视图的位置(x,y)和大小(宽度,高度)。

您应使用self.popularView.bounds.origin.xself.popularView.bounds.origin.y代替self.popularView.frame.minXself.popularView.frame.minY