ios - 使用 Interface Builder 创建了 UIButton。现在我想使用约束更改该按钮的位置和大小
问题描述
移除高度锚点后,下面是输出
精确常数截图
下面是视图控制器的设计。从 IB 截取屏幕截图。
我想更改使用 Interface Builder 创建的 UIButton 的位置和大小。我正在使用约束以编程方式进行。也学习约束。我已经编写了约束代码。请帮我。
let size = self.view.frame.size.height -
(self.layer.frame.size.height + (self.navigationController?.navigationBar.frame.height)! + 20)
channelShowBtn?.translatesAutoresizingMaskIntoConstraints = false
channelShowBtn!.topAnchor.constraint(equalTo:self.view.topAnchor , constant:(((20 + (navigationController?.navigationBar.frame.height)!) + self.layer.frame.height))).isActive = true
channelShowBtn!.heightAnchor.constraint(equalToConstant:size).isActive = true
channelShowBtn!.widthAnchor.constraint(equalToConstant:39).isActive = true
位置和大小应该改变,但实际上并没有改变。
解决方案
您可以从 xib 本身设置位置。
我在下面附上了图片,您可以根据需要设置宽度、高度、前导、尾随、顶部和底部约束。
在这里你可以看到 Add New Constraints 选项在这里你可以根据需要定位按钮
制作高度约束出口:
@IBOutlet var heightConst: NSLayoutConstraint!
现在在视图中是否根据设备加载设置高度
if (UIDevice.current.screenType == .iPhones_5_5s_5c_SE){
heightConst.constant = 400
}else{
heightConst.constant = 200
}
将 UIDevice 扩展添加到您的代码(您也可以在此链接中找到:如何在 swift 中以编程方式检查 iphone 4 和 iphone 5 的屏幕尺寸):
extension UIDevice {
var iPhoneX: Bool {
return UIScreen.main.nativeBounds.height == 2436
}
var iPhone: Bool {
return UIDevice.current.userInterfaceIdiom == .phone
}
enum ScreenType: String {
case iPhones_4_4S = "iPhone 4 or iPhone 4S"
case iPhones_5_5s_5c_SE = "iPhone 5, iPhone 5s, iPhone 5c or iPhone SE"
case iPhones_6_6s_7_8 = "iPhone 6, iPhone 6S, iPhone 7 or iPhone 8"
case iPhones_6Plus_6sPlus_7Plus_8Plus = "iPhone 6 Plus, iPhone 6S Plus, iPhone 7 Plus or iPhone 8 Plus"
case iPhones_X_XS = "iPhone X or iPhone XS"
case iPhone_XR = "iPhone XR"
case iPhone_XSMax = "iPhone XS Max"
case unknown
}
var screenType: ScreenType {
switch UIScreen.main.nativeBounds.height {
case 960:
return .iPhones_4_4S
case 1136:
return .iPhones_5_5s_5c_SE
case 1334:
return .iPhones_6_6s_7_8
case 1792:
return .iPhone_XR
case 1920, 2208:
return .iPhones_6Plus_6sPlus_7Plus_8Plus
case 2436:
return .iPhones_X_XS
case 2688:
return .iPhone_XSMax
default:
return .unknown
}
}
}
推荐阅读
- c++ - std C++17 不支持 CPPUNIT 吗?
- selenium - 我可以使用 selenium 达到某个点,然后使用 request + lxml(或其他包,如 scrapy)来加快处理速度吗?
- linux - Azure Linux Web 应用程序,通过 FTP 部署,文件提供 404
- java - 无法构建 react-native-navigation v1
- loops - 从 For 循环中获取值的批处理脚本
- ios - 对齐指南()不覆盖子视图
- r - 基于条件的回合百分比
- unity3d - 在 Unity 和原始装备中查找骨骼旋转之间的偏移量
- r - R使用数据类型dbl创建带有NA的tibble行
- sql - 如何在 Sqlite3 中跟踪查询慢的原因?