如何初始化let text属性

时间:2018-10-02 10:36:09

标签: swift uikit

我有一个前景色的文本属性,我想在属性字符串中使用。该属性是我班上的let常量,我想用一个UIColor对其进行初始化,然后将其传递给班级的init

class LocationOptions {
    let live : NSAttributedString.Key!
    let black = [NSAttributedString.Key.foregroundColor: UIColor.black]
    let grey = [NSAttributedString.Key.foregroundColor: UIColor.gray]
    let findingLocation: NSAttributedString!
    let centralLondon: NSAttributedString!
    let allLondon: NSAttributedString!


init(color: UIColor){
        live = [NSAttributedString.Key.foregroundColor: color]
        findingLocation = NSAttributedString(string: "Finding Location...", attributes: grey)
        centralLondon = NSAttributedString(string: "Central London", attributes: black)
        allLondon = NSAttributedString(string: "All London", attributes: black)
    }
    ....

使用此代码,当我分配live时,编译器会出现错误:

不能将类型为[NSAttributedString.Key:UIColor]的值分配为类型为NSAttributedString.Key

如果我将live的声明更改为

let live: NSAttributedString.Key.foregroundColor!

当我声明live时,编译器会提示错误:

静态让'foregroundColor'不是'NSAttributedString.Key'的成员类型

如何初始化这样的文本属性?

3 个答案:

答案 0 :(得分:0)

那是因为它需要属性字典。

//This is only key and you cannot assign a attribute to it 
let live = NSAttributedString.Key! 

//this is only value
let live: NSAttributedString.Key.foregroundColor!

These won't work。使它们起作用的方式如下:

class LocationOptions {
    let live: [NSAttributedString.Key : Any]

    init(color: UIColor) {
        live = [NSAttributedString.Key.foregroundColor: color]
    }
}

答案 1 :(得分:0)

问题在这里...

height: 100%

let live : NSAttributedString.Key! 的类型为live,但您正在为其分配字典。

如果NSAttributedString.Key!是一种颜色,请使用:

live

如果它是属性字典,请使用:

let live : UIColor

答案 2 :(得分:0)

只需将module load software/abaqus/abaqus_2018 module load intel-studio-2018 input_file=DIC.inp working_dir=/work/user ### Create ABAQUS environment file for current job, you can set/add your own options (Python syntax) env_file=custom_v6.env ######################################################################### cat << EOF > ${env_file} mp_file_system = (DETECT,DETECT) EOF usub_lib_dir=/home/carwolff/ node_list=$(scontrol show hostname ${SLURM_NODELIST} | sort -u) mp_host_list="[" for host in ${node_list}; do mp_host_list="${mp_host_list}['$host', ${SLURM_CPUS_ON_NODE}]," done mp_host_list=$(echo ${mp_host_list} | sed -e "s/,$/]/") echo "mp_host_list=${mp_host_list}" >> ${env_file} ### Set input file and job (file prefix) name here job_name=${SLURM_JOB_NAME} ### ABAQUS parallel execution #abaqus job=${job_name} input=${input_file} user=mcd_acustom.f cpus=${SLURM_NTASKS} standard_parallel=all interactive #mp_mode=mpi #abaqus make -library mcd_acustom.f abaqus job=${job_name} input=${input_file} cpus=2 standard_parallel=all interactive 声明为

live

let live: [NSAttributedString.Key : UIColor]! 不能是NSAttributedString.Key.foregroundColor!的类型,因为它不是类型,而是属性。通过将live声明为live,您可以为其分配字典,同时能够以更简单的方式初始化[NSAttributedString.Key : UIColor]