gpt4 book ai didi

ios - 如何通过标签定义标签

转载 作者:行者123 更新时间:2023-11-28 14:53:22 25 4
gpt4 key购买 nike

我尝试制作一团标签,但我无法确定按下了哪个标签,以更改它的颜色。如果我像 viewq.viewWithTag(1) 一样使用它,但我如何理解我按下的标签?为改变值(value)。也许我需要上课?因为我想要(如果你按一次,设置红色和一些 Action ,如果再次设置蓝色并做一些 Action )

//
// ViewController.swift
// weqddwqd
//
// Created by Jacket on 4/2/18.
// Copyright © 2018 TryFit. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var viewq: UIView!

var arrq: [String] = ["Hello", "World", "of", "Tags"]
var tags: [Int] = Array()

override func viewDidLoad() {
super.viewDidLoad()

createTagsLabel(arrq)
}
}

extension ViewController {

func createTagsLabel(_: [String]) {

var xPos:CGFloat = 15.0
var ypos: CGFloat = 130.0
var tag: Int = 0

for word in arrq {

let width = word.widthOfString(usingFont: UIFont(name:"verdana", size: 13.0)!)

let checkWholeWidth = CGFloat(xPos) + CGFloat(width) + CGFloat(13.0) + CGFloat(25.5)
if checkWholeWidth > UIScreen.main.bounds.size.width - 30.0 {
xPos = 15.0
ypos = ypos + 29.0 + 8.0
}

let textlable = UILabel(frame: CGRect(x: xPos, y: ypos, width: width + 18, height: 18))
textlable.layer.borderWidth = 1.8
textlable.layer.cornerRadius = 8
textlable.layer.borderColor = UIColor(red:0.00, green:0.48, blue:1.00, alpha:1.0).cgColor
textlable.textColor = UIColor(red:0.00, green:0.48, blue:1.00, alpha:1.0)

textlable.text = word
textlable.font = UIFont(name: "verdana", size: 13.0)
textlable.textAlignment = .center
textlable.isUserInteractionEnabled = true
ypos = ypos + 25

textlable.tag = tag
tags.append(tag)
tag = tag + 1

let tap = UITapGestureRecognizer(target: self, action: #selector(self.tapFunction(_:)))
//textlable.addTarget(self, action: #selector(tapFunction(_:)), for: .touchUpInside)

textlable.addGestureRecognizer(tap)
viewq.addSubview(textlable)
}
}

func tapFunction(_ recognizer: UITapGestureRecognizer) {
print(viewq.viewWithTag(1))

let tag = viewq.viewWithTag(1) as! UILabel
tag.layer.borderColor = UIColor .red.cgColor
tag.textColor = UIColor .red
print("Added")
}
}

extension String {

func widthOfString(usingFont font: UIFont) -> CGFloat {
let fontAttributes = [NSFontAttributeName: font]
let size = self.size(attributes: fontAttributes)
return size.width
}

func heightOfString(usingFont font: UIFont) -> CGFloat {
let fontAttributes = [NSFontAttributeName: font]
let size = self.size(attributes: fontAttributes)
return size.height
}
}

最佳答案

您的 tapFunction 可以轻松地从手势中获取点击 View 。不需要标签:

func tapFunction(_ recognizer: UITapGestureRecognizer) {
if let tappedLabel = recognizer.view as? UILabel {
tappedLabel.layer.borderColor = UIColor.red.cgColor
tappedLabel.textColor = .red
print("Added")
}
}

关于ios - 如何通过标签定义标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49619533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com