ios - Swift - 以编程方式定位 UIButton 的问题(通用)

标签 ios iphone uibutton sprite-kit swift2

我正在尝试将我制作的应用程序从“iPhone”转换为“通用”,我已经成功地调整了大小并定位了除我制作的 UIButtons 之外的所有内容。每次我测试应用程序时,UIButtons 在所有 iPhone 上都完美定位,但当我在 iPad 设备上运行和测试它时,UIButtons 总是定位不同(示例包括:我的按钮变长、重叠、重新定位等) 下面的代码让我得到了最好的结果:

import SpriteKit
import UIKit
import GameKit

class GameScene: SKScene, SKPhysicsContactDelegate, GKGameCenterControllerDelegate {

var PlayButton : UIButton!
var GameCenterButton : UIButton!

override func didMoveToView(view: SKView) {

    PlayButton = UIButton(frame: CGRect(x: 0, y:0, width: view.frame.size.width / 3, height: 60))
    PlayButton.center = CGPoint(x: view.frame.size.width / 2 - 70, y: view.frame.size.height / 1.275)
    PlayButton.setTitle("Play", forState: UIControlState.Normal)
    PlayButton.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
    PlayButton.addTarget(self, action: Selector("plyGame"), forControlEvents: UIControlEvents.TouchUpInside)
    self.view?.addSubview(PlayButton)
    let PlayButtonImage = UIImage(named: "RBI") as UIImage!
    _  = UIButton(type: UIButtonType.Custom)
    PlayButton.setImage(PlayButtonImage, forState: UIControlState.Normal)

    GameCenterButton = UIButton(frame: CGRect(x: 0, y:0, width: view.frame.size.width / 3, height: 60))
    GameCenterButton.center = CGPoint(x: view.frame.size.width / 2 + 70, y: view.frame.size.height / 1.275)
    GameCenterButton.setTitle("gc", forState: UIControlState.Normal)
    GameCenterButton.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
    GameCenterButton.addTarget(self, action: Selector("Ldboards"), forControlEvents: UIControlEvents.TouchUpInside)
    self.view?.addSubview(GameCenterButton)
    let GameCenterButtonImage = UIImage(named: "GCI") as UIImage!
    _  = UIButton(type: UIButtonType.Custom)
    GameCenterButton.setImage(GameCenterButtonImage, forState: UIControlState.Normal)
}

旁注:我使用的是 Xcode 7.1 和 Swift 2.0 语法

最佳答案

我会建议你在这种情况下使用自动布局,并尝试对 button 进行约束。例如,如果你想给按钮宽度是屏幕宽度的 0.33,那么给这样的约束

    let constraint = NSLayoutConstraint(item: button, attribute: .Width, relatedBy: .Equal, toItem: button.superview, attribute: .Width, multiplier: 0.33, constant: 0)

self.view.addConstraint(约束)

关于ios - Swift - 以编程方式定位 UIButton 的问题(通用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34714690/

相关文章:

ios - 自定义相机 iOS

ios - dyld : Symbol not found: _OBJC_CLASS_$_Reachability, Xcode 11 崩溃

iphone - 如何将登录信息附加到文本文件

ios - 如何将 UIButton 添加到地标? ios objective-c

objective-c - 单击时更改按钮背景颜色

ios - 使用 UIButton Action 在 UITableViewCell 中呈现一个弹出窗口

ios - Xcode 8 生成.strings 文件

iOS 核心蓝牙 :Sending data from central and getting response from peripheral

ios - 一个 .h 和 .m 文件用于多个 xib ios

iphone - 函数 ZAssert 的隐式声明在 C99 中无效