XCode/Swift 无法更改文本标签位置
XCode/Swift cannot change text label position
我试图随机更改标签在我屏幕上的位置,但它不起作用。但是,如果我打开一个新的 xcode 项目,同样的代码也可以工作。另外,请注意我的代码底部的打印语句。实际上,每次调用该函数时它都会打印不同的位置,但不会更改标签的位置。
func displayCurrGoal() {
self.label.text = "heyyy"
// Find the labels width and height
let labelWidth = self.label.frame.width
let labelHeight = self.label.frame.height
// Find the width and height of the enclosing view
let labelViewWidth = self.label.superview!.bounds.width
let labelViewHeight = self.label.superview!.bounds.height
// Compute width and height of the area to contain the labels center
let labelXwidth = labelViewWidth - viewWidth
let labelYheight = labelViewHeight - viewHeight
// Generate a random x and y offset
let viewXoffset = CGFloat(arc4random_uniform(UInt32(labelXwidth)))
let viewYoffsset = CGFloat(arc4random_uniform(UInt32(labelYheight)))
// Offset the labels center by the random offsets.
self.label.center.x = viewXoffset + labelWidth / 2
self.label.center.y = viewYoffset + labelHeight / 2
//test if coordinate is changing every time func is called
println(self.label.center.y) }
此外,未启用自动格式设置。
- 你看到屏幕上显示的标签了吗?
- 你看到文本被更改为 "heyyy" 了吗?
label.constraints()
return是什么意思?
- 尝试将位置设置为硬编码数字
正常 view.center.x = 100
有效
这是正确的方法,所以你必须使用 cocoapods 或其他东西。如果是这样,您使用的 imageview 可能是固定的,所以您需要尝试不同的东西...
我试图随机更改标签在我屏幕上的位置,但它不起作用。但是,如果我打开一个新的 xcode 项目,同样的代码也可以工作。另外,请注意我的代码底部的打印语句。实际上,每次调用该函数时它都会打印不同的位置,但不会更改标签的位置。
func displayCurrGoal() {
self.label.text = "heyyy"
// Find the labels width and height
let labelWidth = self.label.frame.width
let labelHeight = self.label.frame.height
// Find the width and height of the enclosing view
let labelViewWidth = self.label.superview!.bounds.width
let labelViewHeight = self.label.superview!.bounds.height
// Compute width and height of the area to contain the labels center
let labelXwidth = labelViewWidth - viewWidth
let labelYheight = labelViewHeight - viewHeight
// Generate a random x and y offset
let viewXoffset = CGFloat(arc4random_uniform(UInt32(labelXwidth)))
let viewYoffsset = CGFloat(arc4random_uniform(UInt32(labelYheight)))
// Offset the labels center by the random offsets.
self.label.center.x = viewXoffset + labelWidth / 2
self.label.center.y = viewYoffset + labelHeight / 2
//test if coordinate is changing every time func is called
println(self.label.center.y) }
此外,未启用自动格式设置。
- 你看到屏幕上显示的标签了吗?
- 你看到文本被更改为 "heyyy" 了吗?
label.constraints()
return是什么意思?- 尝试将位置设置为硬编码数字
正常 view.center.x = 100
有效
这是正确的方法,所以你必须使用 cocoapods 或其他东西。如果是这样,您使用的 imageview 可能是固定的,所以您需要尝试不同的东西...