简体   繁体   中英

Constraint Issues With Custom Keyboard

I'm having a problem adding constraints to the views in my custom keyboard. I've simplified my problem here, just note I do plan on adding a lot more subviews so don't worry about my keyboard not having a "next keyboard" button or anything like that. What I want is to make sure the black square is always centered in the keyboard's view where the view looks like this: 键盘视图

Without constraints, I get this on an iPhone4s-5s: iPhone4s预览

Which is exactly what I want. Only problem is that on a 6 I get this: iPhone6预览

Which is clearly off center, and we can't have that. So I added some constraints on the center square (width and height = 90, and align to center x and y of superview), but then I get this on iPhone4s: iPhone4s预览版2

And I get something similar in every simulator. I've tried adjusting the size of the view when it gets loaded from the nib, but no dice. How can I center that square?

I was toying around with this and found the solution. It has to do with when you load the nib in the view controller. My code for that looks like this (the solution is just one line, marked with a comment)

var kView: UIView!

override func viewDidLoad() {
    super.viewDidLoad()
    loadInterface()
}

func loadInterface() {
    var kNib = UINib(nibName: "TrapType", bundle: nil)
    kView = kNib.instantiateWithOwner(self, options: nil)[0] as! UIView
    let screenSize: CGRect = UIScreen.mainScreen().bounds
    //Below is the line that solved the problem. 
    kView.frame = view.frame
    view.addSubview(kView)
    view.backgroundColor = kView.backgroundColor
}

From what I understand, self.view automagically gets set to the right size, but subviews you may add don't have the same luxury, so just setting the frame. Honestly, it's something I probably should have been aware of in the first place, but there you have it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM