ios - View 的宽度和高度在定向后不会改变

标签 ios swift uiviewcontroller

我使用 xibs 并以编程方式完成大部分工作。不接触 Storyboard。我只想使用 Storyboard进行导航。

我的问题是,在方向 View 高度和宽度保持不变之后。应用运行后如何在纵向和方向模式下获取宽度和高度。

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, HeaderStyle1Delegate, FieldStyle1Delegate, ButtonStyle1Delegate {

var tableStyle = UITableView()
var header: HeaderStyle1!

override func viewDidLoad() {
    super.viewDidLoad()
    createView() // call function for create header, table and regis xib/UINib
}

func createView() {

    //Create Header
    header = HeaderStyle1(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 80))
    header.delegate = self
    self.view.addSubview(header)

    //Create TableView
    tableStyle.frame = CGRect(x: 0, y: 80, width: self.view.frame.size.width, height: self.view.frame.size.height - 80)
    tableStyle.delegate = self
    tableStyle.dataSource = self
    tableStyle.backgroundColor = UIColor(red: 245.0/255.0, green:
        248.0/255.0, blue: 252.0/255.0, alpha: 1.0)
    tableStyle.separatorColor = UIColor.clear
    tableStyle.allowsSelection = false
    tableStyle.isScrollEnabled = true
......
...
..
}

截图

enter image description here

enter image description here

我的 View Controller 。 (正如我提到的,它是空的)

enter image description here

最佳答案

在这些情况下最好使用约束而不是重置框架

header.translatesAutoresizingMaskIntoConstraints = false

if #available(iOS 11, *) {

    let guide = view.safeAreaLayoutGuide

    header.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true

    header.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true

    header.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true

} else {


    header.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true

    header.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true

    header.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true


}

header.heightAnchor.constraint(equalToConstant: 80.0).isActive = true

关于ios - View 的宽度和高度在定向后不会改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48754353/

相关文章:

iOS 获取键盘窗口

uiviewcontroller - willTransitionToTraitCollection 不会被调用,为什么?

ios - 从包含 YouTube 视频的 webView 返回时,如何防止我的 MPMoviePlayerController 变黑 - iOS

ios - 如何在iOS8中将通知类型从横幅更改为警报?

iOS RunLoop 和 DispatchQueue.main.async

string - 如何检查一个字符串是否包含一个int? - swift

ios - 从 UIViewController 导航到 SwiftUI View

ios - 如何让一个自由下落的 Sprite 节点坐在另一个水平移动的 Sprite 身上

ios - Google map /PlacePicker ios api - 有没有办法将附近的地点作为 GMSplace 列表?

json - 解析字典行为奇怪